Javascript中带范围的数字的正则表达式
我在玩正则表达式,注意到下面的代码返回Javascript中带范围的数字的正则表达式,javascript,regex,Javascript,Regex,我在玩正则表达式,注意到下面的代码返回true。有人能解释为什么吗 console.log(/\d{4,12}$/.test('123456789001234567890')\d{4,12}查看字符串是否包含正确的4到12位数字。如果您想限制这一点,可以使用锚定标记-^作为字符串的开头,使用$作为字符串的结尾,如下所示: ^\d{4,12}$或分别/^\d{4,12}$/ 现在,从字符串的开头到结尾,只能显示4到12个字符。您应该在模式的开头和结尾使用字符^和$。在此过程中,您声明正在查找以数
true
。有人能解释为什么吗
console.log(/\d{4,12}$/.test('123456789001234567890')
\d{4,12}
查看字符串是否包含正确的4到12位数字。如果您想限制这一点,可以使用锚定标记-^
作为字符串的开头,使用$
作为字符串的结尾,如下所示:
^\d{4,12}$
或分别/^\d{4,12}$/
现在,从字符串的开头到结尾,只能显示4到12个字符。您应该在模式的开头和结尾使用字符
^
和$
。在此过程中,您声明正在查找以数字开头的字符串,该字符串的位数可以是4到12。根据您在问题中的评论和编辑,您可以使用以下正则表达式:
/^(?:[a-z]*\d){4,8}[a-z]*$/gim
正则表达式分解:
^ - 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
g - Global search
i - Ignore case Match
m - Multiline mode
标志:
^ - 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
g - Global search
i - Ignore case Match
m - Multiline mode
您可以检查字符串中是否有4到12个数字,中间是否有一些非数字
console.log(/^\D*(\D\D*){4,12}$/.test('a78b96');
console.log(/^\D*(\D\D*){4,12}$/.test('a786');
log(/^\D*(\D\D*){4,12}$/.test('a1234567890123')代码>请添加一些用例和所需的results@anubhava你能帮我弄清楚问题的第二部分吗?'4-8(数字)和一些字母表'不清楚。你需要用更多的例子来说明。添加了一些例子。请解释正则表达式。尤其是(?:[a-z]*\d){4,8}
。