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.
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)
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)
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)