s="12/15"
r=/((0?[1-9])|(1[0-2])){1}\/((0?[1-9])|(1[0-9])|(2[0-9])|(3[0-1])){1}/g
s.match(r)
> ["12/1"]
I was trying to validate date format mm/dd but the matched string missed the last digit.
Can anyone help? Thanks, Cheng
s="12/15"
r=/((0?[1-9])|(1[0-2])){1}\/((0?[1-9])|(1[0-9])|(2[0-9])|(3[0-1])){1}/g
s.match(r)
> ["12/1"]
I was trying to validate date format mm/dd but the matched string missed the last digit.
Can anyone help? Thanks, Cheng
Share Improve this question edited Jul 23, 2011 at 18:39 mu is too short 435k71 gold badges858 silver badges818 bronze badges asked Jul 23, 2011 at 18:23 chengcheng 6,6967 gold badges26 silver badges27 bronze badges 1-
@mu is too short,
06/31
we can exclude. See my answer. – Kirill Polishchuk Commented Jul 23, 2011 at 18:58
2 Answers
Reset to default 6Use this regex: ^(0?[1-9]|1[0-2])/(0?[1-9]|[12][0-9]|3[01])$
If you want matches in string, use word boundaries, e.g.:
\b(0?[1-9]|1[0-2])/(0?[1-9]|[12][0-9]|3[01])\b
(?x)
^
(
0?[1-9] # 1-9 or 01-09
|
1[0-2] # 10 11 12
)
/
(
0?[1-9] # 1-9 or 01-09
|
[12][0-9] # 10-29
|
3[01] # 30 31
)
$
Large regex:
(?x)
\b(?:
(?<month>
0?[13578]
|
1[02]
)
/
(?<day>
0?[1-9]
|
[12][0-9]
|
3[01]
)
|
(?<month>
0?[469]
|
11
)
/
(?<day>
0?[1-9]
|
[12][0-9]
|
30
)
|
(?<month>
0?2
)
/
(?<day>
0?[1-9]
|
[12][0-9]
)
)
\b
At first I removed some of your brackets.
One possibility to fix your problem is to use anchors
^(0?[1-9]|1[0-2]){1}\/(0?[1-9]|1[0-9]|2[0-9]|3[0-1]){1}$
This would be the solution if your string is only the date. Those anchors ^
and $
ensure that the expression is matched from the start to the end.
See it here online on Regexr
The second possibility is to change the order in your last part.
(0?[1-9]|1[0-2]){1}\/(1[0-9]|2[0-9]|3[0-1]|0?[1-9]){1}
Because the first part 0?[1-9]
matched your 15
your expression succeeded and that was it. If we put this to the end then at first it tries to match the numbers consisting of two digits, then it matches the 15