admin管理员组文章数量:1425704
Could someone please tell me why this RegEx fails? /
^(\+[0-9]+ )[1-9]{2,} [0-9]{2,}(\-[0-9]+|)$
The funny thing is - when I test it at / it works. But in my code it fails.
Could someone please tell me why this RegEx fails? http://jsfiddle/SrKPG/
^(\+[0-9]+ )[1-9]{2,} [0-9]{2,}(\-[0-9]+|)$
The funny thing is - when I test it at http://jsregex./ it works. But in my code it fails.
Share Improve this question edited Oct 9, 2013 at 12:09 Shikiryu 10.2k9 gold badges52 silver badges76 bronze badges asked Oct 9, 2013 at 12:04 SteveSteve 1845 silver badges16 bronze badges 03 Answers
Reset to default 3The reason you're failing to match is because your second sequence of numbers does not accept zeroes:
^([+][0-9]+ )[1-9]{2,} [0-9]{2,}(\-[0-9]+|)$
+43 660 1234556
It fails because you write it as a string, without escaping the \
.
You could write
var regex = "^(\\+[0-9]+ )[1-9]{2,} [0-9]{2,}(\\-[0-9]+|)$";
But, instead of using a string and the RegExp constructor, you should directly use a regex literal :
text.match(/^(\+[0-9]+ )[1-9]{2,} [0-9]{2,}(\-[0-9]+|)$/g);
You were also refusing 0
in the middle, which doesn't ply with your test string. It seems that what you want is
text.match(/^(\+[0-9]+ )[0-9]{2,} [0-9]{2,}(\-[0-9]+|)$/g);
Yours
"^(\+[0-9]+ )[1-9]{2,} [0-9]{2,}(\-[0-9]+|)$"
Correct
"^(\\+[0-9]+ )[1-9]{2,} [0-9]{2,}(-[0-9]+|)$"
The double escaping is a requirement of JavaScript string literals. It has nothing to do with regex.
Upon parsing your program your string literal bees "^(+[0-9]+ )[1-9]{2,} [0-9]{2,}(-[0-9]+|)$"
in memory, because \+
(as opposed to, let's say, \n
) has no meaning in JS strings.
At this time the regex engine plains about the lone +
that follows nothing.
Note that the something-or-nothing (something|)
is better written as (something)?
.
Apart from that: Thou shalt not use regex to validate phone numbers.
EDIT: The proof is in the ments. ;)
本文标签: javascriptRegEx Syntax Errornothing to repeatStack Overflow
版权声明:本文标题:javascript - RegEx Syntax Error - nothing to repeat - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745455648a2659089.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论