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

时间:2017-04-03 14:20:16

标签: python regex

我正在使用Python进行练习,而且我仍然坚持使用re来检测字符串中的日期。

我唯一的问题是,当这一天是" 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')]

感谢您的帮助

2 个答案:

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

答案 1 :(得分:0)

\d*匹配零个或多个数字后跟空格。在' 1st'然而,数字之后是'

\d*是否适合匹配是值得怀疑的。您可能想要一个或多个数字。或者甚至更好地将其限制为最多两位数(例如\d{1,2}),可选地后面跟着',' nd',' rd'或者'。