regex - javascript regular expression validate mmdd - Stack Overflow

s="1215"r=((0?[1-9])|(1[0-2])){1}((0?[1-9])|(1[0-9])|(2[0-9])|(3[0-1])){1}gs.match(r)&

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
Add a ment  | 

2 Answers 2

Reset to default 6

Use 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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742346470a4426644.html

相关推荐

  • regex - javascript regular expression validate mmdd - Stack Overflow

    s="1215"r=((0?[1-9])|(1[0-2])){1}((0?[1-9])|(1[0-9])|(2[0-9])|(3[0-1])){1}gs.match(r)&

    3小时前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信