2015-06-20 55 views
0

我想匹配日期格式爲(月dd,yyyy)的字符串中的日期。當我在下面使用我的正則表達式模式時,我感到困惑。它只匹配以日期開頭的字符串。我錯過了什麼?日期正則表達式python

>>> p = re.compile('[A-z]{3}\s{1,}\d{1,2}[,]\s{1,}\d{4}') 
>>> s = "xyz Dec 31, 2013 - Jan 4, 2014" 
>>> print p.match(s).start() 
Traceback (most recent call last): 
File "<stdin>", line 1, in <module> 
AttributeError: 'NoneType' object has no attribute 'start' 

>>> s = "Dec 31, 2013 - Jan 4, 2014" 
>>> print p.match(s).start() 
0 #Correct 

回答

1

使用搜索方法而不是匹配。匹配比較整個字符串,但搜索找到匹配的部分。

1
p = re.compile(r'.*?[A-Za-z]{3}\s{1,}\d{1,2}[,]\s{1,}\d{4}') 

match從start.if開始字符串相匹配的作用是不盡相同它將fail.In第一個例子xyz[A-Za-z]{3}被消耗,但該字符串的其餘部分將不匹配。

你可以直接使用你的正則表達式與re.findall並得到結果而不關心比賽的位置。

2

使用re.findall而不是re.match,它會回報給你所有比賽的名單:

>>> s = "Dec 31, 2013 - Jan 4, 2014" 
>>> r = re.findall(r'[A-z]{3}\s{1,}\d{1,2}[,]\s{1,}\d{4}',s) 
>>> r 
['Dec 31, 2013', 'Jan 4, 2014'] 
>>> 
>>> s = 'xyz Dec 31, 2013 - Jan 4, 2014' 
>>> r = re.findall(r'[A-z]{3}\s{1,}\d{1,2}[,]\s{1,}\d{4}',s) 
>>> r 
['Dec 31, 2013', 'Jan 4, 2014'] 

Python docs

re.match(pattern, string, flags=0)如果零個或多個字符在 開始串的匹配正則表達式模式,返回一個 對應的MatchObject實例

在另一方面:

findall()匹配所有出現的圖案的,不只是第一個 作爲搜索()一樣。