I was trying to match a date pattern 25.8.2020 using regex pattern. I used [\d]{1,2}.[\d]{1,2}.[\d]{4} for matching this. But the problem is that if there are some sequence like 454.9451, 2021-2022 etc they are also getting matched. How can i write a regex pattern for matching exactly only dd.mm.yyyy format
2 Answers
I would suggest using strptime to validate the date string in your expected format:
def validate(date_text):
try:
datetime.datetime.strptime(date_text, '%d.%m.%Y')
except ValueError:
raise ValueError("invalid date string " + date_text)
inp = ['25.8.2020', '2020-12-31']
for i in inp:
validate(i)
This prints:
ValueError: invalid date string 2020-12-31
The potential advantage of using strptime over a pure regex is that the latter might also admit strings which match the pattern but are invalid dates. For example, the pattern \d{2}\.\d{2}\.\d{4} by itself would allow for dates such as 30.02.2021, which don't really exist.