最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - javascript regular expression validate mmdd - Stack Overflow

programmeradmin1浏览0评论
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

发布评论

评论列表(0)

  1. 暂无评论