python中使用re选择字符串的问题

python中使用re选择字符串的问题,python,regex,Python,Regex,我正在用Python做一个练习,我被困在这一部分,我必须使用re来检测字符串中的日期 我唯一的问题是,当日期为“1”时,它输出一个空白字符串。我做错了什么 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)

我正在用Python做一个练习,我被困在这一部分,我必须使用re来检测字符串中的日期

我唯一的问题是,当日期为“1”时,它输出一个空白字符串。我做错了什么

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')]

感谢您的帮助

您可以强制使用至少一个数字(使用
\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')]

\d*
匹配零次或多次出现的后跟空格的数字。然而,在“1”中,数字后面跟着“s”


\d*
是否匹配是值得怀疑的。您可能需要一个或多个数字。或者甚至最好将其限制为最多两个数字(例如,
\d{1,2}
),可选地后跟“st”、“nd”、“rd”或“th”。

st没有任何匹配项。请注意,
[A-Z]
与空格不匹配,
\d*
也将匹配0位数字。非常好!谢谢:)