Date Detection:
Write a regular expression that can detect dates in the DD/MM/YYYY format.
Assume that the days range from 01 to 31, the months range from 01 to 12, and the years range from 1000 to 2999. Note that if the day or month is a single digit, it’ll have a leading zero.
Then store these strings into variables named month, day, and year, and write additional code that can detect if it is a valid date.
April, June, September, and November have 30 days, February has 28 days, and the rest of the months have 31 days. February has 29 days in leap years. Leap years are every year evenly divisible by 4, except for years evenly divisible by 100, unless the year is also evenly divisible by 400. Note how this calculation makes it impossible to make a reasonably sized regular expression that can detect a valid date.
import re
def check_date(day, month, year):
# April, June, September, November = 30 days/ February = 28 days, unless leapyear so 29/ rest has 31 days
month_dict = {4: 30, 6: 30, 9: 30, 11: 30, 2: 28}
day_bound = month_dict.get(month, 31)
# month is february
if day_bound == 28:
# checks if the year is a leap year
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
day_bound = 29
else:
day_bound = 29
# if the day is in the range of possible days
if day <= day_bound:
return True
return False
# DD/MM/YYYY
string = "31/02/2020"
date_regex = re.compile(r"([0-2]\d|3[01])/(0\d|1[0-2])/([12]\d{3})")
match = date_regex.search(string)
valid = False
if match:
day = int(match.group(1))
month = int(match.group(2))
year = int(match.group(3))
valid = check_date(day, month, year)
if valid:
print(f'Day: {day}, Month: {month}, Year: {year}')
else:
print('Invalid Date!')