简体   繁体   English

javascript正则表达式验证mm / dd

[英]javascript regular expression validate mm/dd

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. 我试图验证日期格式mm / dd,但匹配的字符串错过了最后一位数字。

Can anyone help? 有人可以帮忙吗? Thanks, Cheng 谢谢,程

Use this regex: ^(0?[1-9]|1[0-2])/(0?[1-9]|[12][0-9]|3[01])$ 使用这个正则表达式: ^(0?[1-9]|1[0-2])/(0?[1-9]|[12][0-9]|3[01])$

If you want matches in string, use word boundaries, eg: 如果你想在字符串中匹配,使用单词边界,例如:

\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 在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. 因为第一部分0?[1-9]与你的15匹配,你的表达成功了,就是这样。 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 如果我们把它放到最后,那么首先它会尝试匹配由两位数组成的数字,然后它匹配15

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM