正则表达式判断日期是否合法
时间: 2023-08-30 10:12:51 浏览: 270
要判断日期是否合法,可以使用正则表达式结合日期的具体规则来进行匹配。以下是一个示例代码:
```python
import re
def is_valid_date(date_string):
pattern = r'^(?:(?:(?:1[6-9]|[2-9]\d)\d{2})-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1\d|2[0-8])|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:(?:1[6-9]|[2-9]\d)(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))-02-29)$'
if re.match(pattern, date_string):
return True
else:
return False
date1 = '2022-01-01'
date2 = '2022-02-29'
date3 = '2022-13-01'
date4 = '2023-02-30'
print(is_valid_date(date1)) # True
print(is_valid_date(date2)) # True
print(is_valid_date(date3)) # False
print(is_valid_date(date4)) # False
```
在这个示例中,正则表达式使用了较为复杂的模式来匹配日期,包括了年份、月份和日期的具体规则。如果日期字符串符合规定的格式和规则,则返回 True,否则返回 False。你可以根据自己的需求进行调整和扩展。请注意,这里仅仅是通过正则表达式进行格式和规则的初步判断,并不能完全保证日期的合法性,后续还需要进一步验证。
阅读全文
相关推荐


















