我想匹配具有以下格式的日期:
2010-08-27, 2010/08/27
现在我不是很在意日期是否实际可行,只是它的格式正确。
请告诉这个正则表达式。
谢谢
原文由 user1308308 发布,翻译遵循 CC BY-SA 4.0 许可协议
我想匹配具有以下格式的日期:
2010-08-27, 2010/08/27
现在我不是很在意日期是否实际可行,只是它的格式正确。
请告诉这个正则表达式。
谢谢
原文由 user1308308 发布,翻译遵循 CC BY-SA 4.0 许可协议
您可以使用此代码:
import re
# regular expression to match dates in format: 2010-08-27 and 2010/08/27
# date_reg_exp = re.compile('(\d+[-/]\d+[-/]\d+)')
更新了下面的正则表达式:
# regular expression to match dates in format: 2010-08-27 and 2010/08/27
# and with mixed separators 2010/08-27
# date_reg_exp = re.compile('\d{4}[-/]\d{2}[-/]\d{2}')
# if separators should not be mixed use backreference:
date_reg_exp = re.compile('\d{4}(?P<sep>[-/])\d{2}(?P=sep)\d{2}')
# a string to test the regular expression above
test_str= """
fsf2010/08/27sdfsdfsd
dsf sfds f2010/08/26 fsdf
asdsds 2009-02-02 afdf
"""
# finds all the matches of the regular expression and
# returns a list containing them
matches_list=date_reg_exp.findall(test_str)
# iterates the matching list and prints all the matches
for match in matches_list:
print match
原文由 Thanasis Petsas 发布,翻译遵循 CC BY-SA 3.0 许可协议
4 回答4.4k 阅读✓ 已解决
4 回答3.8k 阅读✓ 已解决
1 回答3.1k 阅读✓ 已解决
3 回答2.1k 阅读✓ 已解决
1 回答4.4k 阅读✓ 已解决
1 回答3.9k 阅读✓ 已解决
1 回答2.8k 阅读✓ 已解决
您可以使用
datetime
模块来解析日期:输出:
所以捕获
ValueError
会告诉你日期是否匹配:为了允许各种格式,您可以测试所有可能性,或使用
re
首先解析字段: