使用python正则表达式匹配日期

use*_*308 14 python regex python-3.x

我想匹配具有以下格式的日期:

2010-08-27,2010/08/27

现在我不太关注日期实际可行,但只是它的格式正确.

请告诉正则表达式.

谢谢

hoc*_*chl 23

您可以使用该datetime模块来解析日期:

import datetime

print datetime.datetime.strptime('2010-08-27', '%Y-%m-%d')
print datetime.datetime.strptime('2010-15-27', '%Y-%m-%d')
Run Code Online (Sandbox Code Playgroud)

输出:

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'
Run Code Online (Sandbox Code Playgroud)

所以抓住ValueError会告诉你日期是否匹配:

def valid_date(datestring):
    try:
        datetime.datetime.strptime(datestring, '%Y-%m-%d')
        return True
    except ValueError:
        return False
Run Code Online (Sandbox Code Playgroud)

要允许各种格式,您可以测试所有可能性,或者用于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
Run Code Online (Sandbox Code Playgroud)


Tha*_*sas 12

您可以使用此代码:

import re

# regular expression to match dates in format: 2010-08-27 and 2010/08/27 
# date_reg_exp = re.compile('(\d+[-/]\d+[-/]\d+)')
Run Code Online (Sandbox Code Playgroud)

更新正则表达式如下:

# 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
Run Code Online (Sandbox Code Playgroud)


jam*_*lak 5

使用datetime模块。尽管您不应该使用它,但为了知识起见,这是一个正则表达式:

r'\d{4}[-/]\d{2}[-/]\d{2}'
Run Code Online (Sandbox Code Playgroud)