1

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 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Try this: [0-3]*\d\.[01]*\d\.\d{4} Using \. instead .

Example: regex101

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.