-1

I'd like to know how to make the year to be mandatory with 4 digits

reference: https://stackoverflow.com/a/26972181/3541735

my regex is tweaked a little bit not to permit "/" or "." and only numbers for months:

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

Debuggex Demo

  • `{4,}` is what you're searching for. But this regex is so complex....takes some time to figure out where to put that... – Jeff Apr 09 '18 at 14:23
  • 1
    This seems like something that would be better solved by validating the output from `DateTime::createFromFormat` – iainn Apr 09 '18 at 14:25
  • For a pure regex solution, I have modified the regex to make 4 digits for the year mandatory. Albeit, the regex is a bit convoluted. – Brandon Krueger Apr 24 '18 at 19:41

1 Answers1

0

Requiring 4 digits for the year was a little bit tricky given the complexity of the regex, but with the help of Debuggex I was able to find the three locations where a ? allowed the year to be specified as either 2 or 4 digits. By removing these three occurrences of ?, the year is now required to include all 4 digits. Otherwise, the first 2 digits were optional.

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

Here is a visual representation of the updated regex. Note that three of the bypass loops no longer appear on the first two digits on the year.

visual regex