I am writing a regular expression to match the strings MySQL accepts when assigning to a DATETIME column.
The regular expression needs to match these strings:
2016-07-12 06:32:54.0001
2016-07-12 06:32:54.
2016-07-12 06:32:54
2016-07-12 06:32:
2016-07-12 06:32
2016-07-12 06:
2016-07-12 06
2016-07-12
2016-07-12
But should not match these strings:
2016-07-12 06:32:.0001
2016-07-12 06::54.0001
2016-07-12 :32:54.0001
2016-07-12 ::.
That is, every part after and including the middle space is optional, but each optional part depends on the previous part (the regex can only skip remaining parts to go straight to the end).
Currently I have:
/^
(\d+) # year
[[:punct:]]
(\d+) # month
[[:punct:]]
(\d+) # day
(?:
(?:T|\s+|[[:punct:]]) # seperator between date and time
(?:
(\d+) # hour
(?:
[[:punct:]]
(?:
(\d+) # minute
(?:
[[:punct:]]
(?:
(\d+) # second
(?:
\.
(\d+)? # microsecond
)?
)?
)?
)?
)?
)?
)?
$/xDs
Is there a way to avoid the deeply nested groups?
Thanks