This python program used regular expressions to determine whether a given date is correct or not. Leap years and days in a month are calculated as well.
First, we can import re, and any other library that might be useful.
import re
In order to check whether a date is correct, we need to know how many days there are in each month. This dictionary has the month paired with the amount of days in it, so that we can easily use it later.
month_dict = {"01":31, "02":28, "03":31, "04":30, "05":31, "06":30, "07":31, "08":31, "09":30, '10':31, '11':30, '12':30}
Next, we need to create our regex. In this format, the date will be split by forward slashes, and include zeroes when there are no tens.
date_regex = re.compile(r'((0\d|1[0-2])/([0-3]\d)/([0-2]\d\d\d))')
mo = date_regex.search("02/29/2020"
We also need to write a function that can determine if the year is a leap year, which can help us in determining if the date is valid.
def is_leap_year(year):
if (year % 4) == 0 and (year % 100) != 0:
return True
else:
return False
The final step would be creating the conditionals. Here is where the dictionary comes in; we use it to check if the day is wrong for the month of the input date. Then, we use the previous function to check for leap year, and if its February. If everything is successful, we determine that the input is in fact a date.
if mo:
month, day, year = mo.group(2), mo.group(3), mo.group(4)
int_year = int(year) #this was made for troubleshooting
if month == "02" and is_leap_year(int_year): #first we check if its leap year and the month is February
if int(day) > 29:
print("Incorrect date(February)")
else:
print("Match found - " + mo.group())
elif int(day) <= month_dict[month]: #if its March of a non leap year, we #look at the month dictionary to check the date
print("Match found - " + mo.group())
else:
print("Incorrect date(day)")
else:
print("No matches found")