JavaScript: \\d{4} RegExp 允许超过 4 位数字 [英] JavaScript: \\d{4} RegExp allows more than 4 digits
问题描述
对文本输入的年份值进行以下验证:
Have following validation for year value from text input:
if (!year.match(new RegExp('\\d{4}'))){
...
}
RegExp
等于 null
如果数字从 0 到 3.没关系.
如果是 4 位数字,则返回值.没关系.
如果超过 4 位,它再次返回值,那就是不正常.
RegExp
equals null
if numeric of digits from 0 to 3. It's OK.
In case 4 digits it returns value.It's OK.
In case more than 4 digits it returns value again,that it's NOT OK.
文档说 {n}
声明意味着确切的数字,但工作方式如下:
Documentation says {n}
declaration means exact number,but works like:
exact+
有了如此丑陋的验证,它就可以正常工作了:
With such ugly validation it work's fine:
if (!year.match(new RegExp('\\d{4}')) || year.length>4){
...
}
我只想使用 RegExp 对象.
I wish to utilize RegExp object only.
推荐答案
是的,它允许超过 4 位数字,因为它是部分匹配,使用 ^
和 $
标记字符串的开头和结尾.
Yes it would allow more than 4 digits since it would be a partial match use the ^
and $
to mark the beginning and the end of the string.
if (!year.match(new RegExp('^\\d{4}$'))){
...
}
这篇关于JavaScript: \\d{4} RegExp 允许超过 4 位数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!