2017-04-03 70 views
3

我正在做一個Python練習,而且我被困在這個部分,我必須使用re來檢測字符串中的日期。在python中用字符串選擇的問題

我唯一的問題是,當一天是「1st」時,它輸出一個空白字符串。我究竟做錯了什麼?

import re 
text = "article 1st May 1988; another article 2 June 1992, some new article 25 October 2001; " 

result = re.findall(r'(\d*) ([A-Z]\w+) (\d+)',text) 
print(result) 

輸出

[('', 'May', '1988'), ('2', 'June', '1992'), ('25', 'October', '2001')] 

感謝您的幫助

+0

'st'與任何東西都不匹配。請注意,'[A-Z]'與空格不匹配,'\ d *'也將匹配0個數字。 –

回答

3

你可能迫使至少一個數字(與\d+,而不是僅僅\d*),並添加可能的字符串的子集序:

import re 
text = "article 1st May 1988; another article 2 June 1992, some new article 25 October 2001; " 

result = re.findall(r'(\d+(?:st|nd|rd|th)?) ([A-Z]\w+) (\d+)',text) 
print(result) 
# [('1st', 'May', '1988'), ('2', 'June', '1992'), ('25', 'October', '2001')] 
+0

工程太棒了!謝謝 :) – Vectrex28

0

\d*匹配零o r數字後面加空格的次數更多。然而在'1st'後面跟着's'。

\d*是否完全符合要求是值得商榷的。您可能需要一個或多個數字。或者更好的是甚至將其限制爲最多兩位數(例如\d{1,2}),可選地接着'st','nd','rd'或'th'。