Python中的正则表达式日期:英国:日 - 月 - 年

时间:2015-10-15 08:23:56

标签: python regex

我正在尝试使用python编写一个REGEX来识别日期(英国:日 - 月 - 年)。

我写了一些随机字符串,如下所示。

string='these are just rubbish 01-13- 00-00- 44-44- 11-2-2222 24-3-1695abc 12-13-1111 32/11/2000\
        these are actual dates -- 4-02-2011 12/12/1990 31-11-1690  11 July 1990 7 Oct 2012\
        these are actual deal-- by 12 December six people died and  by 18 Nov 19902.00 dollar was spent\
        anomalies -- are he gave June 2000 bucks in 5 July. The shares rose 5% on 5 November 1999.'

re.findall('(\
([1-9]|0[1-9]|[12][0-9]|3[01])\
[-/\s+]\
(1[1-2]|0[1-9]|[1-9]|Jan|January|Feb|February|Mar|March|Apr|April|May|Jun|June|Jul|July|\
Aug|August|Sept|September|Oct|October|Nov|November|Dec|December)\
[-/\s+]\
(1[0-9]\d\d|20[0-2][0-5])\
[^\da-zA-Z])', string)

我得到的输出如下:

[('2/11/2000 ', '2', '11', '2000'),
 ('4-02-2011 ', '4', '02', '2011'),
 ('12/12/1990 ', '12', '12', '1990'),
 ('31-11-1690 ', '31', '11', '1690'),
 ('11 July 1990 ', '11', 'July', '1990'),
 ('7 Oct 2012 ', '7', 'Oct', '2012'),
 ('5 November 1999.', '5', 'November', '1999')]

正则表达式格式似乎有效,但正则表达式无法识别的日期很少:

by **12 December** six people
by **18 Nov** 19902.00 dollar

如何修改正则表达式以便识别上述日期。

2 个答案:

答案 0 :(得分:1)

似乎您的正则表达式仅识别日期,包括年份。

更改具有可选年份部分的规则。 (整个部分其他'十二月'或'十一月')

答案 1 :(得分:1)

你要问的是将年份作为选择。因此,您应该使用可选的非捕获组围绕您的年份[-/\s+](1[0-9]\d\d|20[0-2][0-5])

(?:[-/\s+](1[0-9]\d\d|20[0-2][0-5]))?

此外,它与2/11/2000相匹配,这是“垃圾”的一部分。第一行上的日期。使用\b启动正则表达式,以确保它从单词边界开始。