Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression to match valid dates

Tags:

date

regex

I'm trying to write a regular expression that validates a date. The regex needs to match the following

  • M/D/YYYY
  • MM/DD/YYYY
  • Single digit months can start with a leading zero (eg: 03/12/2008)
  • Single digit days can start with a leading zero (eg: 3/02/2008)
  • CANNOT include February 30 or February 31 (eg: 2/31/2008)

So far I have

^(([1-9]|1[012])[-/.]([1-9]|[12][0-9]|3[01])[-/.](19|20)\d\d)|((1[012]|0[1-9])(3[01]|2\d|1\d|0[1-9])(19|20)\d\d)|((1[012]|0[1-9])[-/.](3[01]|2\d|1\d|0[1-9])[-/.](19|20)\d\d)$ 

This matches properly EXCEPT it still includes 2/30/2008 & 2/31/2008.

Does anyone have a better suggestion?

Edit: I found the answer on RegExLib

^((((0[13578])|([13578])|(1[02]))[\/](([1-9])|([0-2][0-9])|(3[01])))|(((0[469])|([469])|(11))[\/](([1-9])|([0-2][0-9])|(30)))|((2|02)[\/](([1-9])|([0-2][0-9]))))[\/]\d{4}$|^\d{4}$ 

It matches all valid months that follow the MM/DD/YYYY format.

Thanks everyone for the help.

like image 688
NakedBrunch Avatar asked Sep 09 '08 04:09

NakedBrunch


People also ask

Is there a regular expression to detect a valid regular expression?

No, if you are strictly speaking about regular expressions and not including some regular expression implementations that are actually context free grammars. There is one limitation of regular expressions which makes it impossible to write a regex that matches all and only regexes.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).

Which of the following regular expression passes the calendar date?

A regular expression for dates (YYYY-MM-DD) should check for 4 digits at the front of the expression, followed by a hyphen, then a two-digit month between 01 and 12, followed by another hyphen, and finally a two-digit day between 01 and 31.


1 Answers

This is not an appropriate use of regular expressions. You'd be better off using

[0-9]{2}/[0-9]{2}/[0-9]{4} 

and then checking ranges in a higher-level language.

like image 127
Chris Conway Avatar answered Sep 25 '22 14:09

Chris Conway