我有一个日期字符串,例如Thursday, December 13, 2018,即DAY, MONTH dd, yyyy,我需要使用正则表达式对其进行验证。

正则表达式不应验证不正确的日期或月份。例如,Muesday, December 13, 2018Thursday, December 32, 2018应该标记为无效。

到目前为止,我所能做的就是为“,”,“ dd”和“ yyyy”编写表达式。我不明白如何以仅接受正确的日期和月份名称的方式自定义正则表达式。

我的尝试:

^([something would come over here for day name]day)([\,]|[\, ])(something would come over here for month name)(0?[1-9]|[12][0-9]|3[01])([\,]|[\, ])([12][0-9]\d\d)$


谢谢。

编辑:我只包括从1000年开始的年份-2999年。验证leap年无关紧要。

最佳答案

您可以尝试为像您这样的“复杂”案例实现正则表达式的库。这称为日期查找器。

这个家伙为您完成了工作,可以在文本中找到任何日期:

https://github.com/akoumjian/datefinder

要安装:pip install datefinder

import datefinder

string_with_dates = "entries are due by January 4th, 2017 at 8:00pm
    created 01/15/2005 by ACME Inc. and associates."

matches = datefinder.find_dates(string_with_dates)

for match in matches:
    print(match)

# Output
2017-01-04 20:00:00
2005-01-15 00:00:00


要检测“周二”之类的错误单词,您可以使用PyEnchant这样的拼写检查器过滤文本

import enchant
>>> d = enchant.Dict("en_US")
>>> print(d.check("Monday"))
True
>>> print(d.check("Muesday"))
False
>>> print(d.suggest("Muesday"))
['Tuesday', 'Domesday', 'Muesli', 'Wednesday', 'Mesdames']

关于python - 如何编写正则表达式以验证DAY,MONTH dd,yyyy类型的日期格式?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53759224/

10-14 12:41
查看更多