Anybody can help compose regular expression for this logic?
MM/DD/YYYY hh:mm AM/PM
MM/DD/YYYY hh AM/PM
MM/DD/YYYY
MM/YYYY
YYYY
[Date templates]
M/D/YY
M/YY
M/YYYY
M/D/YYYY
MMM YY
MMM YYYY
MMMM YY
MMMM YYYY
YY/M
YY-M
YY.M
YYYY/M
YYYY-M
YYYY.M
YYYY
YYYY/M/D
YYYY-M-D
YYYY.M.D
M-D-YY
M-YY
M-YYYY
M-D-YYYY
M.D.YY
M.YY
M.YYYY
M.D.YYYY
MMM D[,] YY
MMM D[,] YYYY
MMMM D[,] YY
MMMM D[,] YYYY
D MMM[,] YY
D MMM[,] YYYY
D MMMM[,] YY
D MMMM[,] YYYY
[Time templates]
hh:mm AM (or PM or A or P)
hh AM (or PM or A or P)
HH:mm
YY two-digit year (00 => 2000, 10 => 2010)
To give you some hints:
You have different ways to specify a month: M, MM, MMMM
M means its a number, so you can write it like
[0-9](there are even more compact ways, but I think this requires the least explanation).MM means you can have another digit, but this digit can obviously only be
1, as12is the highest.So we alter the expression:
1?[0-9]. Which means the one is optional.Is this correct? No, because it would e.g. accept
0as a valid month. So alter it again.(1[0-2]|[1-9])which means: either a1followed by another digit between 0 and 2, so 10, 11, 12 are accepted. The braces are there to create a group.Now to accept
MMMM(1[0-2]|[1-9]|January|February)etc.This can be further composed, e.g. for
MM/YYYYandYYYY((1[0-2]|[1-9]|January|February)/)?<YYYY-Pattern>Also don’t forget to match the start and the beginning:
^((1[0-2]|[1-9]|January|February)/)?<YYYY-Pattern>$otherwise you’d match things like
abc MM/DD/YYYY blaIf everything works, you should use non-capturing groups where you don’t need to reference the contents of a group. So
^((1[0-2]|[1-9]|January|February)/)?<YYYY-Pattern>$becomes^(?:(1[0-2]|[1-9]|January|February)/)?<YYYY-Pattern>$because you probably don’t need to reference the group with the/. (However I think this is implementation dependent). To reference the groupse you probably want to give them names. Have a look here: http://www.regular-expressions.info/named.htmlWell that’s the way I compose regular expressions…
Don’t give up, its going to be a longer expression, but not a very complex one.