合并多个正则表达式以进行日期识别



我正在编写一个python 2.7.6程序,该程序可以在输入文件中查找日期的所有实例,即(如果文件包含"April 9th,2014"Tuesday"02/14/1980"Christmas")。由于日期可以用许多不同的方式表示,我为不同类型的日期分别使用了正则表达式。我想把我所有单独的正则表达式合并成一个大的正则表达式,这样它就可以按照文件中出现的顺序找到每个"类型"的日期。

我有以下代码来测试日期,如"2014年4月9日">

matches = re.findall("(?:((?:jan(?:(?:.)?|(?:uary)?)|feb(?:(?:.)?|(?:ruary)?)|mar(?:(?:.)?|(?:ch)?)|apr(?:(?:.)?|(?:il)?)|may|jun(?:(?:.)?|(?:e)?)|jul(?:(?:.)?|(?:y)?)|aug(?:(?:.)?|(?:gust)?)|sep(?:(?:.)?|(?:ept(?:(?:.)?))?|(?:tember)?)|oct(?:(?:.)?|(?:ober)?)|nov(?:(?:.)?|(?:ember)?)|dec(?:(?:.)?|(?:ember)?)) (?:[123][0-9]|[1-9])[ trfv]?(?:rd|st|th)?(?:,)?[ trfv]?(?:[0-2][0-9][0-9][0-9])?)|(?:(?:[0]?[1-9])|(?:[1][0-2]))[-/](?:(?:[012]?[0-9])|(?:[3][01]))[/-][12][0-9][0-9][0-9])",fileText,re.IGNORECASE)
print matches

在下一行,我匹配类似于1980年2月14日的日期,就像这个

matches = re.findall("(?:(?:[0]?[1-9])|(?:[1][0-2]))[-/](?:(?:[012]?[0-9])|(?:[3][01]))[/-][12][0-9][0-9][0-9]",fileText, re.IGNORECASE)
print matches

我想把它们合并成一个正则表达式。我试着做

matches = re.findall("(?:first regular expression|second regular expression)", textFile, re.IGNORECASE)
print matches

但这只是打印了所有日期,如"2014年4月9日"(这是第一个正则表达式的含义)和",用于所有看起来像"1980年2月14日"的日期(这是第二个正则表达式。

如果能帮我弄清楚如何将2个regex变成1,我们将不胜感激。

根据每个正则表达式检查每个输入行怎么样?

for line in input_file:
regex1 = re.findall(pattern,line)
regex2 = re.findall(pattern,line)
if len(regex1) > 0:
for item in regex1:
print(item)
if len(regex2) > 0:
for item in regex2:
print(item)

最新更新