[英]match dates using python regular expressions
我要匹配具有以下格式的日期:
2010-08-27、2010 / 08/27
現在,我對實際可行的日期不是很確定,只是日期格式正確。
請告訴正則表達式。
謝謝
您可以使用datetime
模塊來解析日期:
import datetime
print datetime.datetime.strptime('2010-08-27', '%Y-%m-%d')
print datetime.datetime.strptime('2010-15-27', '%Y-%m-%d')
輸出:
2010-08-27 00:00:00
Traceback (most recent call last):
File "./x.py", line 6, in <module>
print datetime.datetime.strptime('2010-15-27', '%Y-%m-%d')
File "/usr/lib/python2.7/_strptime.py", line 325, in _strptime
(data_string, format))
ValueError: time data '2010-15-27' does not match format '%Y-%m-%d'
因此,捕獲ValueError
會告訴您日期是否匹配:
def valid_date(datestring):
try:
datetime.datetime.strptime(datestring, '%Y-%m-%d')
return True
except ValueError:
return False
要允許各種格式,您可以測試所有可能性,或使用re
首先解析字段:
import datetime
import re
def valid_date(datestring):
try:
mat=re.match('(\d{2})[/.-](\d{2})[/.-](\d{4})$', datestring)
if mat is not None:
datetime.datetime(*(map(int, mat.groups()[-1::-1])))
return True
except ValueError:
pass
return False
您可以使用以下代碼:
import re
# regular expression to match dates in format: 2010-08-27 and 2010/08/27
# date_reg_exp = re.compile('(\d+[-/]\d+[-/]\d+)')
更新了以下正則表達式:
# regular expression to match dates in format: 2010-08-27 and 2010/08/27
# and with mixed separators 2010/08-27
# date_reg_exp = re.compile('\d{4}[-/]\d{2}[-/]\d{2}')
# if separators should not be mixed use backreference:
date_reg_exp = re.compile('\d{4}(?P<sep>[-/])\d{2}(?P=sep)\d{2}')
# a string to test the regular expression above
test_str= """
fsf2010/08/27sdfsdfsd
dsf sfds f2010/08/26 fsdf
asdsds 2009-02-02 afdf
"""
# finds all the matches of the regular expression and
# returns a list containing them
matches_list=date_reg_exp.findall(test_str)
# iterates the matching list and prints all the matches
for match in matches_list:
print match
使用datetime
模塊。 為了您的知識,這里是一個正則表達式,盡管您不應該使用它:
r'\d{4}[-/]\d{2}[-/]\d{2}'
dateutil軟件包具有非常智能的日期解析器。 它解析各種日期格式。 http://pypi.python.org/pypi/python-dateutil
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.