1

i was trying to match the dates starting from year 1900 to 2017 in dd/mm/yyyy format using this

^(0[1-9]|1[0-9]|2[0-9]|3[01])/(0[1-9]|1[012])/(19[0-9]{2}|20[0-1][0-7])$

regular expression but i am observing that this regular expression fails for dates like 16/06/2008 and 21/02/2008.
To make sure that all the parts of this regular expression are working or not i tried its all three parts like ^(0[1-9]|1[0-9]|2[0-9]|3[01])$ , ^(0[1-9]|1[012])$ and ^(19[0-9]{2}|20[0-1][0-7])$ on different sets of days months and years but i found that these are working fine but when i ran it combined i got same unexpected result for date like 16/06/2008.

Additionally i want to inform you that i am using this regex in javascript :

var patt = new RegExp("^(0[1-9]|1[0-9]|2[0-9]|3[01])/(0[1-9]|1[012])/(19[0-9]{2}|20[0-1][0-7])$");
var res = patt.exec(datestring);

for dates like 16/06/2008 res evaluates to null.

Please let me know where i am going wrong i? To solve this i have gone through some regular expression tutorials and previously asked questions but i did not find any relavent answer that can tell me why this regex fails for some specific dates. Please help.

Jan
  • 42,290
  • 8
  • 54
  • 79

2 Answers2

9

Because 2008 doesn't match 20[0-1][0-7]

Andrey Belykh
  • 2,578
  • 4
  • 32
  • 46
0

Along with

20[0-1][0-7]

not matching the year 2008 (8 does not fall in the range [0-7]) you may also want to escape the forward slashes in the regex by using a backslash as below

^(0[1-9]|1[0-9]|2[0-9]|3[01])\/(0[1-9]|1[012])\/(19[0-9]{2}|20[0-1][0-9])$
Adam M.
  • 1,023
  • 1
  • 10
  • 21