python中re的字符串选择问题

2024-04-25 22:25:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用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')]

谢谢你的帮助


Tags: 字符串textimportrenewarticleanothersome
2条回答

您可以强制至少一个数字(使用\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*匹配零次或多次出现的后跟空格的数字。但是,在“1st”中,数字后跟“s”。你知道吗

有人怀疑\d*是否完全匹配。您可能需要一个或多个数字。或者最好将其限制为最多两个数字(例如\d{1,2}),可选地后跟“st”、“nd”、“rd”或“th”。你知道吗

相关问题 更多 >