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. ;)
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745455648a4628473.html
评论列表(0条)