Javascript 长度为 4、5 或 6 的数字的正则表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7864971/
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
Regular expression for number with length of 4, 5 or 6
提问by Ghyath Serhal
I need a regular expression that validate for a number with length 4, 5, 6
我需要一个正则表达式来验证长度为 4、5、6 的数字
I used ^[0-9]{4} to validate for a number of 4, but I do not know how to include validation for 5 and 6.
我使用 ^[0-9]{4} 来验证 4 的数量,但我不知道如何包括对 5 和 6 的验证。
回答by James
Try this:
尝试这个:
^[0-9]{4,6}$
{4,6}
= between 4 and 6 characters, inclusive.
{4,6}
= 4 到 6 个字符(含)。
回答by Andy Mabbett
[0-9]{4,6}
can be shortened to \d{4,6}
[0-9]{4,6}
可以缩短为 \d{4,6}
回答by xanatos
Be aware that, as written, Peter's solution will "accept" 0000
. If you want to validate numbers between 1000
and 999999
, then that is another problem :-)
请注意,正如所写,彼得的解决方案将“接受” 0000
。如果你想验证之间的数字1000
和999999
,那是另一个问题:-)
^[1-9][0-9]{3,5}$
for example will block inserting 0
at the beginning of the string.
例如将阻止0
在字符串的开头插入。
If you want to accept 0 padding, but only up to a lengh of 6, so that 001000
is valid, then it becomes more complex. If we use look-ahead then we can write something like
如果您想接受 0 填充,但最多只能接受 6 的长度,因此这001000
是有效的,那么它会变得更加复杂。如果我们使用前瞻,那么我们可以写出类似的东西
^(?=[0-9]{4,6}$)0*[1-9][0-9]{3,}$
This first checks if the string is long 4-6 (?=[0-9]{4,6}$)
, then skips the 0s 0*
and search for a non-zero [1-9]
followed by at least 3 digits [0-9]{3,}
.
这首先检查字符串是否长 4-6 (?=[0-9]{4,6}$)
,然后跳过 00*
并搜索[1-9]
后跟至少 3 个数字的非零[0-9]{3,}
。
回答by SteeveDroz
If the language you use accepts {}
, you can use [0-9]{4,6}
.
如果您使用的语言接受{}
,您可以使用[0-9]{4,6}
.
If not, you'll have to use [0-9][0-9][0-9][0-9][0-9]?[0-9]?
.
如果没有,您将不得不使用[0-9][0-9][0-9][0-9][0-9]?[0-9]?
.