Using regex to match date format in yyyymmdd

Joe Wang picture Joe Wang · Mar 27, 2015 · Viewed 30.5k times · Source

The regex should match valid dates in a string in the format YYYYMMDD. For example, aaa_20150327_bbb should be matched but aaa_20150229_bbb not because 2015 is not a leap year.

Only year from 2000 to 2099 need to be considered.

Answer

enrico.bacis picture enrico.bacis · Mar 27, 2015

Total madness (years 0-9999)

The following one (based on this answer) works for years between 0 and 9999.

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

(check the demo)


Total madness simplified (years 2000-2099)

If you want you can simplify it to only work for years between 2000 and 2099.

(?<!\d)(?:(?:20\d{2})(?:(?:(?:0[13578]|1[02])31)|(?:(?:0[1,3-9]|1[0-2])(?:29|30)))|(?:(?:20(?:0[48]|[2468][048]|[13579][26]))0229)|(?:20\d{2})(?:(?:0?[1-9])|(?:1[0-2]))(?:0?[1-9]|1\d|2[0-8]))(?!\d)

But as you can see it's not really more simple.

(check the demo)


The sane way (years *)

To keep your sanity you should stick to a very simple regex and then validate it using code.

(20\d{2})(\d{2})(\d{2})

(check the demo)