简体   繁体   English

如何匹配字符串中的日期模式

[英]How to match a date pattern in strings

I am trying to match any number of correct format dates in a given string.我正在尝试匹配给定字符串中任意数量的正确格式日期 For a date to be in correct format, it has to appear in the form dd-mm-yyyy.要使日期格式正确,它必须以 dd-mm-yyyy 形式出现。 Therefore dd and mm cannot have just one digit, they need 2 and they need to be in the correct range;因此 dd 和 mm 不能只有一位,它们需要 2 并且它们需要在正确的范围内; this means that day has to be between 1 and 31 and month has to be between 1 and 12.这意味着日期必须介于 1 和 31 之间,月份必须介于 1 和 12 之间。

I have it working for one type of input, but it does not match another input.我让它适用于一种类型的输入,但它与另一种输入不匹配。 Here is my code:这是我的代码:

#!/usr/bin/env python
from sys import stdin
from re import compile

myFormat = compile(r'(?=([0-2]\d|3[0-1])-(0\d|1[0-2])-(201[3-5]))' )
print myFormat.findall(stdin.readline())

Input 1:输入 1:

777-444---21-12-2013-12-2013-12-2013---444-777

Output:输出:

[('21', '12', '2013'), ('13', '12', '2013'), ('13', '12', '2013')]

So far so good.到现在为止还挺好。 But if I have the input:但如果我有输入:

0012-10-2012-10-2012

it matches nothing.它不匹配。 The correct output is supposed to be:正确的输出应该是:

[('12', '10', '2012'), ('12', '10', '2012')]

Please help me find the correct regex to do this请帮我找到正确的正则表达式来做到这一点

EDIT编辑

I only want to match only years 2012 to 2015.我只想匹配 2012 年到 2015 年。

If you change your regex to:如果您将正则表达式更改为:

myFormat = compile(r'(?=([0-2]\d|3[0-1])-(0\d|1[0-2])-(201[2-5]))' )

it will work (just change last [3-5] to [2-5] ).它会起作用(只需将最后[3-5]更改为[2-5] )。 Currently it doesn't because you have:目前不是因为你有:

201[3-5]

for the year part, so it refuses to match 2012.对于年份部分,因此它拒绝匹配 2012 年。

For checking validity:检查有效性:

from sys import stdin
from re import compile
from datetime import datetime
myFormat = compile(r'(?=([0-2]\d|3[0-1])-(0\d|1[0-2])-(201[2-5]))' )
str1=("0012-10-2012-10-2012", "0031-02-2012");
for s in str1:
    for date in myFormat.findall(s):
        (d,m,y) = map(int, date)
        try:
           datetime(y,m,d)
           print date
        except: pass

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM