JavaScript 正则表达式只匹配 X 位数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4840547/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:20:24  来源:igfitidea点击:

JavaScript regular expression to match X digits only

javascriptregexnumbers

提问by magenta placenta

Can someone help my pea brain figure out why my simple regular expression is not working as I am expecting/wanting it to.

有人可以帮助我的豌豆大脑弄清楚为什么我的简单正则表达式不能像我期望/想要的那样工作。

I want to match a date format of MM/DD/YYYY with exactly2 and 4 digits, so something like 01/16/1955. My code below does that, but it also matches 2+and 4+digits, so something like 011/16/1955 or 01/16/19555 (1 extra digit) pass my validation as well.

我想匹配MM / DD / YYYY与日期格式正好2和4位数,所以像1955年1月16日。我下面的代码可以做到这一点,但它也匹配2+4+位数字,因此诸如 011/16/1955 或 01/16/19555(1 个额外数字)之类的内容也通过了我的验证。

//validate date of birth
var dob_label    = $date_of_birth.find('label').text().slice(0, -1),
dob_mm           = $dob_mm.val(),
dob_dd           = $dob_dd.val(),
dob_yyyy         = $dob_yyyy.val(),     
regex_two_digit  = /^\d{2}$/,
regex_four_digit = /^\d{4}$/;

if ( (regex_two_digit.test(dob_mm)) && (regex_two_digit.test(dob_dd)) && (regex_four_digit.test(dob_yyyy)) ) {
    //a button is enabled here
} else {
    //a validation error is thrown here and the button is disabled
}

回答by Crayon Violent

need to specify start and end of string

需要指定字符串的开始和结束

/^\d{4}$/

回答by Darrell Robert Parker

try this ^\d{1,2}\/\d{1,2}\/\d{4}$

尝试这个 ^\d{1,2}\/\d{1,2}\/\d{4}$