Skip to content

Instantly share code, notes, and snippets.

@xuzheng465
Last active October 18, 2024 09:36
Show Gist options
  • Save xuzheng465/091c2a0ed698125a06e9e6b1a17a0db6 to your computer and use it in GitHub Desktop.
Save xuzheng465/091c2a0ed698125a06e9e6b1a17a0db6 to your computer and use it in GitHub Desktop.
正则表达式处理日期格式YYYY-MM-DD
import re
pattern = r'''
^
(?!1582-10-(0[5-9]|1[0-4])$)
(?:
# 匹配31天的月份
(?:
(?!1582-10)
(?:[0-2]\d{3})-(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])
)
|
# 匹配30天的月份
(?:[0-2]\d{3})-(?:0[469]|11)-(?:0[1-9]|[12]\d|30)
|
# 匹配2月份的情况
(?:
# 闰年的情况
(?:
# 能被400整除的年份
(?:[0-2](?:0[48]|[2468][048]|[13579][26])00)
|
# 能被4整除但不能被100整除的年份
(?:[0-2]\d{2}(?:0[48]|[2468][048]|[13579][26])(?!00))
)
-02-(?:0[1-9]|1\d|2[0-9])
|
# 平年的情况
(?:[0-2]\d{3})-02-(?:0[1-9]|1\d|2[0-8])
)
)
$
'''
regex = re.compile(pattern, re.VERBOSE)
dates = [
'1582-10-04',
'1582-10-05',
'1582-10-14',
'1582-10-15',
'1582-10-31',
'2023-02-28',
'2024-02-29',
'2023-02-29',
'2023-04-30',
'2023-04-31',
'2999-12-31',
'3000-01-01'
]
for date in dates:
if regex.match(date):
print(f"{date} 是有效日期")
else:
print(f"{date} 是无效日期")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment