我想從字符串中解析出所有日期(可能以不同的形式寫入)。問題是可能有一個日期寫在這種形式d/m -y
例如22/11 -12。但是也可能有一個日期用這種形式d/m
寫成,沒有指定年份。如果我在這個包含更長形式的字符串中找到日期,我不希望它以更短的形式再次找到。這是我的代碼失敗的地方,它找到了第一個日期兩次(一年與一年,一次沒有它)。確保兩個正則表達式找不到相同的結果
我真的有兩個問題:(1)做這件事的「正確」方法是什麼?看來我真的從錯誤的角度來解決這個問題。 (2)如果我應該堅持這樣做的話,那麼這條線datestring.replace(match.group(0), '')
怎麼會不刪除日期以至於我再也找不到了?
這是我的代碼:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
dformats = (
'(?P<day>\d{1,2})/(?P<month>\d{1,2}) -(?P<year>\d{2})',
'(?P<day>\d{1,2})/(?P<month>\d{1,2})',
'(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})',
)
def get_dates(datestring):
"""Try to extract all dates from certain strings.
Arguments:
- `datestring`: A string containing dates.
"""
global dformats
found_dates = []
for regex in dformats:
matches = re.finditer(regex, datestring)
for match in matches:
# Is supposed to make sure the same date is not found twice
datestring.replace(match.group(0), '')
found_dates.append(match)
return found_dates
if __name__ == '__main__':
dates = get_dates('1/2 -13, 5/3 & 2012-11-22')
for date in dates:
print date.groups()
很好的回答,恭喜! – georg
Emacs抱怨你不遵循pep-8 ;-)否則一個很好的答案。儘管在正則表達式中使用'|'這不是處理相同名稱組的簡單方法,但我困擾了我。有6行處理這個問題(!): -/ –
Niclas:是的,我編輯了它大約3次,可能仍然沒有正確的答案:)另外,是的,我很沮喪,RE引擎didn'讓我重新使用這些名稱,我可以創建一個簡單的函數來重新映射以清理代碼。如果我們可以假設我們總是將PERIOD-X拷貝到PERIOD,如果dayX存在,X在範圍內(1,4),PERIOD在['day','month','year'],那麼這只是一個幾行。任何更復雜的處理可能都必須像上面那樣分解它。 –