gpt4 book ai didi

python - 如何编写正则表达式来验证 DAY、MONTH dd、yyyy 类型的日期格式?

转载 作者:行者123 更新时间:2023-11-30 22:02:38 25 4
gpt4 key购买 nike

我有一个像 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 年开始的年份。验证闰年并不重要。

最佳答案

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

这个人为你完成了在文本中查找任何类型的日期的工作:

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

要检测像“Muesday”这样的错误单词,您可以使用拼写检查器过滤文本,例如 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com