[英]Regular Expression for number with range in Javascript
I was playing with regular expression and noticed that the below code is returning true
. 我在使用正则表达式,发现以下代码返回true
。 Can any one explain why? 谁能解释为什么?
console.log(/\\d{4,12}$/.test('12345678901234567890'));
How can I have limited number of digits say, 4-8(number of digits) and some alphabets in my regular expression? 如何在正则表达式中使用有限的数字(例如4-8(数字))和一些字母? Ex- ('abc7896' -> true, 'a78b96' -> true, etc) 例如(('abc7896'-> true,'a78b96'-> true等)
\\d{4,12}
looks if the string contains 4 to 12 digits which is correct. \\d{4,12}
查看字符串是否包含 4到12位正确的数字。 If you want to limit this, you can use the anchor tags - ^
for beginning and $
for end of string like this: 如果要限制此范围,则可以使用锚标记- ^
表示字符串的开头, $
表示字符串的结尾,如下所示:
^\\d{4,12}$
or respectively /^\\d{4,12}$/
^\\d{4,12}$
或/^\\d{4,12}$/
Now from the beginning to the end of the string, only 4 to 12 characters can appear. 现在,从字符串的开头到结尾,只能显示4到12个字符。
You should use the characters ^
and $
at the start and at the end of your pattern. 您应该在模式的开头和结尾使用字符^
和$
。 Doing so you state that you are looking for a string that starts with a digit and it can have any number of digits from 4 to 12. 这样做是为了表明您正在寻找以数字开头的字符串,并且该字符串可以包含4到12之间的任意数字。
Based on your comments and edits in your question, you may use this regex: 根据您对问题的评论和修改,可以使用以下正则表达式:
/^(?:[a-z]*\d){4,8}[a-z]*$/gim
RegEx Breakup: 正则表达式分解:
^ - Start
(?: - Start non-capturing group
[a-z]*\d - Match 0 or more alphabets followed by a digit
){4,8} - End non-capturing group. [4,8} matches it 4 to 8 times
[a-z]* - Match trailing 0 or more alphabets in input
$ - End
Flags: 标志:
g - Global search
i - Ignore case Match
m - Multiline mode
You could check if there are 4 to 12 digits in the string with some non digits inbetween. 您可以检查字符串中是否有4到12位数字,中间有一些非数字。
console.log(/^\\D*(\\d\\D*){4,12}$/.test('a78b96')); console.log(/^\\D*(\\d\\D*){4,12}$/.test('a786')); console.log(/^\\D*(\\d\\D*){4,12}$/.test('a1234567890123'));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.