'Regex to accept multiple date formats

So here's what I need to identify Dates with Formatted as: 1/2/2022 01/02/2022 01/2/2022 1/02/20202

So basically, date formats like: mm/dd/yyyy m/d/yyyy mm/d/yyyy m/dd/yyyy m/d/yyyy

As much as I hate it, the files that I get are always a mix of these date formats.

I've tried this regex format

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

But It can't seem to get some dates.



Solution 1:[1]

In a naïve simple way, this regex will match strings with those date stamps

^(?:[0-3]?\d[\/]){2}\d{4}$

Basically 2 groups of 1 to 2 digits with a slash, followed by 4 digits.
And the first 2 numbers will range from 0 to 39.
But this would also allow strings like '0/32/0000'

A more specific regex to limit those ranges between 1 and 31 :

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

But this will still allow datestamps like 31/31/2000

If a negative lookahead is added those can be avoided.

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

This won't match something like '15/15/2000'.
But it won't care about how many days a month has.

Test on regex101 here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1