2015-10-15 64 views
2

我正在嘗試使用python編寫一個REGEX來識別日期(英國:日 - 月 - 年)。Python中的正則表達式日期:英國:日 - 月 - 年

我寫了一些隨機字符串,如下所示。

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 

哪有我修改了正則表達式,以便它也能識別上述日期。

回答

1

你要求的是讓年爲可選。所以,你應該有一個可選的非捕獲組環繞你的年部分[-/\s+](1[0-9]\d\d|20[0-2][0-5])

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

此外,它匹配2000年2月11日這是對你的第一行「垃圾」日期的一部分。使用\b開始正則表達式,確保它始於單詞邊界。

+0

嗨Benshepherd,我已經發布了一個小問題,您提供的解決方案和另一個案例在另一篇文章中。你可以找到它http://stackoverflow.com/questions/33145399/pyhton-regex-to-handle-different-types-of-date-written。請提供一些見解。 – Sam

+0

我認爲這是同一問題的一部分。我認爲它會以重複的方式關閉,你應該修改這個問題來解決這兩個問題。 – benshepherd

1

看來你的正則表達式只能識別包括YEAR在內的日期。

更改具有可選年份部分的規則。 (整個部分其他'十二月'或'十一月')