#Program that detects dates in text and copies and prints them
import pyperclip, re
#DD/MM/YEAR format
dateRegex = re.compile(r'(\d\d)/(\d\d)/(\d\d\d\d)')
#text = str(pyperclip.paste())
text = 'Hello. Your birthday is on 29/02/1990. His birthday is on 40/09/1992 and her birthday is on 09/09/2000.'
matches = []
for groups in dateRegex.findall(text):
day = groups[0]
month = groups[1]
year = groups[2]
#convert to int for comparisons
dayNum = int(day)
monthNum = int(month)
yearNum = int(year)
#check if date and month values are valid
if dayNum <= 31 and monthNum > 0 and monthNum <= 12:
#months with 30 days
if month in ('04', '06', '09', '11'):
if not (dayNum > 0 and dayNum <= 30):
print("Invalid date input")
continue
#February only
if month == '02':
#February doesn't have more than 29 days
if dayNum > 29:
continue
if yearNum % 4 == 0:
#leap years have 29 days in February
if yearNum % 100 == 0 and yearNum % 400 != 0:
#not a leap year even if divisible by 4
if dayNum > 28:
continue
else:
if dayNum > 28:
continue
#all other months have up to 31 days
if month not in ('02', '04', '06', '09', '11'):
if dayNum <= 0 and dayNum > 31:
continue
else:
continue
date = '/'.join([groups[0],groups[1],groups[2]])
matches.append(date)
if len(matches) > 0:
pyperclip.copy('\n'.join(matches))
print('Copied to clipboard:')
print('\n'.join(matches))
else:
print('No dates found.')
Became Hot Network Question