0

How to write regexp, matches date-format: String of the form

YYYY-MM-DD 

where MM<12, DD<31

St.Antario
  • 23,179
  • 26
  • 96
  • 243
  • possible duplicate of [Regular Expression to match valid dates](http://stackoverflow.com/questions/51224/regular-expression-to-match-valid-dates) – murgatroid99 Jul 16 '14 at 16:34
  • @murgatroid99 no, there is no suitable regexp in the link you provide – St.Antario Jul 16 '14 at 16:36
  • Replace `/` with `-` and your question is basically a subset of that one. – murgatroid99 Jul 16 '14 at 16:39
  • 1
    This is not something you should be trying to do with a regex - is there a particular reason you wanted a regex for it? – Graham Ritchie Jul 16 '14 at 16:53
  • 2
    @GrahamRitchie I agree... I think matching the date for format with something like "^\d{4}-(\d{2})-(\d{2})$" then checking the matched groups for size constraints is a rather solid approach... but ensuring that MM and DD are less than 12 and 31, respectively, as part of a regex just sounds awful – user3334690 Jul 16 '14 at 17:23
  • According to [RegExLib](http://regexlib.com/(X(1)A(RaY01fMWtMydRcmh5xTt1xgyw8Swd01FMaz6fIjBNpNjvvxiKPRQwAcOerQL5XR6IHlItF6QzyHqv8Zag8v-xX57dsPak_VdzmInG3Q0DUgxJ1MRdDAxYQFecVNb6vkgOUTtHf5RRh4ZytwfAFQuSCJTpsB15H8UVPxPfUP34YwV7y3XwUa5pMjzVk3As-Ap0))/Search.aspx?k=yyyy-mm-dd&c=-1&m=-1&ps=20) `^\d{4}[\-\/\s]?((((0[13578])|(1[02]))[\-\/\s]?(([0-2][0-9])|(3[01])))|(((0[469])|(11))[\-\/\s]?(([0-2][0-9])|(30)))|(02[\-\/\s]?[0-2][0-9]))$` will do what you're looking for. But this is only the first of 23 possibilities. Best of luck. – Bob Jarvis - Reinstate Monica Aug 16 '15 at 21:41

1 Answers1

0

Fast and readable, but not precise:

^\d{4}-\d\d-\d\d$

MM=00..12 DD=00..31? A little bit more precise ( e.g. 2015-00-00 is still possible), but hard to read:

^\d{4}-(0\d|1[0-2])-([0-2]\d|3[01])$

MM=01..12 DD=01..31? To cut out YYYY-00-00, a bit longer:

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

But you asked for MM<12 (not <= 12) and DD < 31, so: MM=00..11 DD=00..30? Right? Then use this:

^\d{4}-(0\d|1[01])-([0-2]\d|30)$

The ^ checks for the start and $ for the end of the string. You can drop it, if the surrounding characters are not interested.

dev.null
  • 528
  • 2
  • 7