Validating date format dd mm yyyy using regular expressions

Nevertheless, I made some improvements to these match groups. Now, group 1 represents the day, group 2 represents the month, group 3 represents the year, group 4 represents the hour, group 5 represents the minute, and group 6 represents the second.
To handle such a complex expression, it might be beneficial to utilize the modifier and incorporate whitespace and comments using the .
Proposal 1:
Here’s a suggestion that allows for days ranging from 00 to 31, months ranging from 00 to 12, and years ranging from 0000 to 2999, requiring 2 digits for the day and month, and 4 digits for the year.


Solution 1:

The following suggestion allows for input of days ranging from 00 to 31, months ranging from 00 to 12, and years ranging from 0000 to 2999, with a requirement of 2 digits for days and months, and 4 digits for years.

^([0-2][0-9]|3[01])-(0[0-9]|1[0-2])-[0-2][0-9]{3}$

The code does not account for months with fewer than 31 days. It is advisable to utilize the date functions provided by the programming language you are using, as they can handle this verification.
Updated to incorporate enhancements suggested by AmigoJack, resulting in a reduction of 7 characters in the regex string without affecting the matching.
Appreciation goes to AmigoJack for the contributions.


Solution 2:


This pattern will identify strings ranging from ’01-01-0000′ to ’31-12-9999′.

^(?:0[1-9]|[12][0-9]|3[01])-(?:0[1-9]|1[012])-[0-9]{4}$

Nevertheless, validation of the string is still required within the programming language.

This pattern remains unaffected by the varying number of days in each month, making it independent of month length. Moreover, incorporating leap years into a pattern to account for February would result in unnecessary complexity.

^(?:0[1-9]|1[0-9]|2[0-8])-(?:0[1-9]|1[0-2])-[0-9]{4}$|^(?:(?:31-(?:0[13578]|1[02]))-|(?:(?:29|30)-(?:0[13-9]|1[0-2])-))(?:(?:1[6-9]|[2-9][0-9])[0-9]{2})$|^(?:29-02-(?:(?:(?:1[6-9]|[2-9][0-9])(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$

Frequently Asked Questions