Python编程快速上手第七章—实践项目【日期检测】
题目描述:
7.18.1日期检测
编写一个正则表达式,可以检测DD/MM/YYY格式的日期,假设日期的范围是01~31,月份的范围是01-12,年份的范围是1000~2999。请注意,如果日期或月份是一位数字,会在前面自动加0。
该正则表达式不必检测每个月或年的正确日期;它将接受不存在的日期,例如31/02/2020或31/04/2021。然后将这些字符串存储到名为 month、day和year的变量中,并编写其他代码以检测它是否为有效日期。4月、6月、9月和11月有30天,2月有28天,其余月份为31天,闰年2月有29天,闰年是能被4整除的年,能被100整除的年除外,除非它能被400整除。这种计算使得用大小合理的正则表达式来检测有效日期成为不可能的事,请注意原因。
代码实现:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @File : reProject1.py 日期检测
import re
dayRegex = re.compile(r'(^(([0-3][1-9])|([1-9])|([1-3]0))/(([0-1][1-9])|[1-9]|10)/([1-2][0-9]{3})$)')
text1 = input('请输入DD/MM/YYYY格式的日期:(日期的范围是01—31,月份的范围是01-12,年份的范围是1000-2999)')
formatdayRegex = re.compile(r'^(\d)/') # 如果日期是一位数字,在日期前自动加零。
text2 = formatdayRegex.sub(r'0\1/', text1)
formatmonthRegex = re.compile(r'/(\d)/') # 如果月份是一位数字,在月份前自动加零。
text3 = formatmonthRegex.sub(r'/0\1/', text2)
mo = dayRegex.search(text3)
def dateCheck(day) :
lst = day.split('/')
day = int(lst[0])
month = int(lst[1])
year = int(lst[2])
if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0) : # 闰年
if month == 2 and day > 29 :
print('请输入正确的日期。')
elif (month == 4 or 6 or 9 or 11) and day > 30 :
print('请输入正确的日期。')
else :
print('日期正确。')
else : # 不是闰年
if month == 2 and day > 28 :
print('请输入正确的日期。')
elif (month == 4 or 6 or 9 or 11) and day > 30 :
print('请输入正确的日期。')
else :
print('日期正确。')
if mo is None :
print('请按照日期格式输入。(日期的范围是01—31,月份的范围是01-12,年份的范围是1000-2999)')
else :
print(mo.group())
date = mo.group()
dateCheck(date)