我读了这个并且很感兴趣:Validating date format using regular expression
所以我开始编写自己版本的日期验证功能,我想我很接近,但并不完全,我想要一些建议和提示。我花了很多时间尝试调整功能。
import re
import datetime
# Return True if the date is in the correct format
def checkDateFormat(myString):
isDate = re.match('[0-1][0-9]\/[0-3][0-9]\/[1-2][0-9]{3}', myString)
return isDate
# Return True if the date is real date, by real date it means,
# The date can not be 00/00/(greater than today)
# The date has to be real (13/32) is not acceptable
def checkValidDate(myString):
# Get today's date
today = datetime.date.today()
myMaxYear = int(today.strftime('%Y'))
if (myString[:2] == '00' or myString[3:5] == '00'):
return False
# Check if the month is between 1-12
if (int(myString[:2]) >= 1 or int(myString[:2]) <=12):
# Check if the day is between 1-31
if (int(myString[3:5]) >= 1 or int(myString[3:2]) <= 31):
# Check if the year is between 1900 to current year
if (int(myString[-4:]) <= myMaxYear):
return True
else:
return False
testString = input('Enter your date of birth in 00/00/0000 format: ')
# Making sure the values are correct
print('Month:', testString[:2])
print('Date:', testString[3:5])
print('Year:', testString[-4:])
if (checkDateFormat(testString)):
print('Passed the format test')
if (checkValidDate(testString)):
print('Passed the value test too.')
else:
print('But you failed the value test.')
else:
print("Failed. Try again")
问题1:int(myString[3:5])
当我想比较它是否有效时,还有其他方法(更好)吗?感觉我的方法很重复,而且这个函数必须要00/00/0000,不然会坏掉。因此,从这个意义上说,该功能并不是那么有用。尤其是我处理我的方式00/01/1989
,只是简单地比较if
他们确实是00
。
问题2:有很多if
语句,不知道有没有更好的方法来编写这个测试?
我想了解更多关于 python 编程的知识,任何建议或建议将不胜感激。非常感谢。