[英]How to match a date pattern in strings
我正在嘗試匹配給定字符串中任意數量的正確格式日期。 要使日期格式正確,它必須以 dd-mm-yyyy 形式出現。 因此 dd 和 mm 不能只有一位,它們需要 2 並且它們需要在正確的范圍內; 這意味着日期必須介於 1 和 31 之間,月份必須介於 1 和 12 之間。
我讓它適用於一種類型的輸入,但它與另一種輸入不匹配。 這是我的代碼:
#!/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())
輸入 1:
777-444---21-12-2013-12-2013-12-2013---444-777
輸出:
[('21', '12', '2013'), ('13', '12', '2013'), ('13', '12', '2013')]
到現在為止還挺好。 但如果我有輸入:
0012-10-2012-10-2012
它不匹配。 正確的輸出應該是:
[('12', '10', '2012'), ('12', '10', '2012')]
請幫我找到正確的正則表達式來做到這一點
我只想匹配 2012 年到 2015 年。
如果您將正則表達式更改為:
myFormat = compile(r'(?=([0-2]\d|3[0-1])-(0\d|1[0-2])-(201[2-5]))' )
它會起作用(只需將最后[3-5]
更改為[2-5]
)。 目前不是因為你有:
201[3-5]
對於年份部分,因此它拒絕匹配 2012 年。
檢查有效性:
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.