Python正则表达式处理不同类型的日期

时间:2015-10-15 09:55:49

标签: python regex

我正在尝试编写一个正则表达式来识别某些日期。

我正在处理的字符串是:

string:
'these are just rubbish 11-2-2222, 24-3-1695-194475 12-13-1111, 32/11/2000\
 these are dates 4-02-2011, 12/12/1990, 31-11-1690,  11 July 1990, 7 Oct 2012\
 these are actual deal- by 12 December six people died and in June 2000 he told, by 5 July 2001, he will leave.'

正则表达式看起来像:

re.findall('(\
[\b, ]\
([1-9]|0[1-9]|[12][0-9]|3[01])\
[-/.\s+]\
(1[1-2]|0[1-9]|[1-9]|Jan|January|Feb|February|Mar|March|Apr|April|May|Jun|June|Jul|July|Aug|August|Sept|September|Oct|October|Nov|November|Dec|December)\
(?:[-/.\s+](1[0-9]\d\d|20[0-2][0-5]))?\
[^\da-zA-Z])',String)

我得到的输出是:

[(' 11-2-', '11', '2', ''),
 (' 24-3-1695-', '24', '3', '1695'),
 (' 4-02-2011,', '4', '02', '2011'),
 (' 12/12/1990,', '12', '12', '1990'),
 (' 31-11-1690,', '31', '11', '1690'),
 (' 11 July 1990,', '11', 'July', '1990'),
 (' 7 Oct 2012 ', '7', 'Oct', '2012'),
 (' 12 December ', '12', 'December', ''),
 (' 5 July 2001,', '5', 'July', '2001')]

问题:

  1. 前两个输出是错误的,它们来自可选表达式((?:[-/.\s+](1[0-9]\d\d|20[0-2][0-5]))?) 处理像"12 December"这样的案件。我该如何摆脱它们?

  2. 有一个案例"June 2000"未被表达式处理 我是否可以使用能够处理此案例的表达式实现某些内容而不影响其他内容?

1 个答案:

答案 0 :(得分:1)

我会避免尝试获取正则表达式来解析您的日期。如您所见,它可以正常运行,但很快就会变得难以捕捉一些极端情况,例如无效日期,例如2018年9月31日

一种更安全的方法是让Python的datetime决定日期是否有效。然后,您可以轻松指定有效的日期范围和允许的日期格式。

此脚本通过使用正则表达式提取所有单词和数字组来工作。然后,它一次包含三个部分,并应用允许的日期格式。如果datetime成功解析给定格式,则将对其进行测试以确保其在您允许的日期范围内。如果有效,匹配的部分将被跳过以避免在部分日期进行第二次匹配。

如果找到的日期不包含年份,则假定为default_year

from itertools import tee
from datetime import datetime
import re


valid_from = datetime(1920, 1, 1)
valid_to = datetime(2030, 1, 1)
default_year = 2018

dt_formats = [
    ['%d', '%m', '%Y'], 
    ['%d', '%b', '%Y'],
    ['%d', '%B', '%Y'],
    ['%d', '%b'],
    ['%d', '%B'],
    ['%b', '%d'],
    ['%B', '%d'],
    ['%b', '%Y'],
    ['%B', '%Y'],
]

text = """these are just rubbish 11-2-2222, 24-3-1695-194475 12-13-1111, 32/11/2000
these are dates 4-02-2011, 12/12/1990, 31-11-1690,  11 July 1990, 7 Oct 2012
these are actual deal- by 12 December six people died and in June 2000 he told, by 5 July 2001, he will leave."""

t1, t2, t3 = tee(re.findall(r'\b\w+\b', text), 3)
next(t2, None)
next(t3, None)
next(t3, None)
triples = zip(t1, t2, t3)

for triple in triples:
    for dt_format in dt_formats:
        try:
            dt = datetime.strptime(' '.join(triple[:len(dt_format)]), ' '.join(dt_format))

            if '%Y' not in dt_format:
                dt = dt.replace(year=default_year)

            if valid_from <= dt <= valid_to:
                print(dt.strftime('%d-%m-%Y'))

                for skip in range(1, len(dt_format)):
                    next(triples)
            break

        except ValueError:
            pass

对于您输入的文本,将显示:

04-02-2011
12-12-1990
11-07-1990
07-10-2012
12-12-2018
01-06-2000
05-07-2001