使用 RE- Python 提取带有文本的不同日期结构

Extract Different Date Structures with Text Using RE- Python

我有日期格式不同的字符串。例如,

sample_str_1 = 'this amendment of lease, made and entered as of the  10th day of august, 2016,   by and between john doe and jane smith'

另外,另一个包含日期的字符串,

sample_str_2 ='this agreement, made and entered as of May 1, 2016, between john doe and jane smith'

为了从第一个字符串中提取日期,我做了这样的事情,

match = re.findall(r'\S+d{4}\s+', sample_str_1)

这给出了一个空列表。

对于第二个字符串,我使用了与第一个字符串相同的方法并得到一个空字符串。

我也尝试了 datefinder 模块,它给了我这样的输出,

import datefinder
match = datefinder.find_dates(sample_str_1)

for m in match:
    print(m)

>> 2016-08-01 00:00:00

以上输出错误,应该是2016-08-10 00:00:00

我尝试了另一种使用旧版 post

的方法
match = re.findall(r'\d{2}(?:january|february|march|april|may|june|july|august|september|october|november|december)\d{4}',sample_str_1)

这又给了我一个空列表。

如何从字符串中提取这样的日期?是否有通用方法来提取具有文本和数字的日期?任何帮助将不胜感激。

正则表达式(?:(\d{1,2})(?:th|nd|rd).* ([a-z]{3})[a-z]*|([a-z]{3})[a-z]* (\d{1,2})),\s*(\d{4})

Python代码:

regex = re.compile('(?:(\d{1,2})(?:th|nd|rd).* ([a-z]{3})[a-z]*|([a-z]{3})[a-z]* (\d{1,2})),\s*(\d{4})', re.I)

for x in regex.findall(text):
    if x[0] == '':
        date = '-'.join(filter(None, x))
    else:
        date = '%s-%s-%s' % (x[1],x[0],x[4])

    print(datetime.datetime.strptime(date, '%b-%d-%Y').date())

输出:

2016-08-10
2016-05-01

Code demo