2016-09-17 80 views
0

可以說我有日期時間格式Python的正則表達式匹配任何順序

12 September, 2016 
September 12, 2016 
2016 September, 12 

我需要的正則表達式像它應該在相同的順序爲上述

match-1 : 12 
match-2 : September 
match-3 : 2016 

給出任何日期格式返回的比賽總是我需要的結果總是以相同的順序。

回答

1

您不能切換組訂單,但你能說出你的組:

(r'(?P<day>[\d]{2})(?:\s|,|\?|$)|(?P<month>[a-zA-Z]+)|(?P<year>[\d]{4})') 
  • (?P<day>[\d]{2})(?:\s|,|\?|$):每天匹配,可以在Python中訪問與l.group("day")

  • (?P<month>[a-zA-Z]+):比賽一個月,可以用Python訪問l.group("month")

  • (?P<year>[\d]{4}):匹配的一年,可以在Python中訪問與l.group("year")

例子:

import re 

data = """ 
12 September, 2016 
September 12, 2016 
2016 September, 12 
September 17, 2012 
17 October, 2015 
""" 

rgx = re.compile(r'(?P<day>[\d]{2})(?:\s|,|\?|$)|(?P<month>[a-zA-Z]+)|(?P<year>[\d]{4})') 

day = "" 
month = "" 
year = "" 

for l in rgx.finditer(data): 
     if(l.group("day")): 
       day = l.group("day") 
     elif(l.group("month")): 
       month = l.group("month") 
     elif(l.group("year")): 
       year = l.group("year") 

     if(day != "" and month != "" and year != ""): 
       print "{0} {1} {2}".format(day, month, year) 
       day = "" 
       month = "" 
       year = "" 

Demo

+0

感謝兄弟!這實際上是我想要的。它的工作原理是... –

0

您無法更改組排序。你需要做3個模式的「或」,然後通過結果來確定哪個組映射到什麼,這應該很簡單。

2

命名組如下建議是這樣做(的一個很好的方式,特別是如果你已經設置了正則表達式),但爲了完成的目的,這裏是如何使用datetime模塊來處理它。

from datetime import datetime as date 

def parse_date(s): 
    formats = ["%d %B, %Y", 
       "%B %d, %Y", 
       "%Y %B, %d"] 

    for f in formats: 
     try: 
      return date.strptime(s, f) 
     except ValueError: 
      pass 

    raise ValueError("Invalid date format!") 

arr = ["12 September, 2016", 
     "September 12, 2016", 
     "2016 September, 12", 
     "12/9/2016"] 

for s in arr: 
    dt = parse_date(s)  
    print(dt.year, dt.strftime("%B"), dt.day) 

""" 

2016 September 12 
2016 September 12 
2016 September 12 
Traceback (most recent call last): 
    File "C:/Python33/datetest.py", line 22, in <module> 
    dt = parse_date(s) 
    File "C:/Python33/datetest.py", line 19, in parse_date 
    raise ValueError("Invalid date format!") 
ValueError: Invalid date format! 

""" 

欲瞭解更多信息,請參閱datetime documentation page

+1

您可能想要滿足數據不符合上述三種格式之一的情況,否則您將冒險得到'NameError' - 或者可能更糟糕,重新使用之前的日期當前一個不匹配... –

+0

好點,固定! – damjan

+0

酷 - 或者 - 你可以把它包裝在一個像[這裏](https://stackoverflow.com/a/23581184) –