最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - RegEx Syntax Error - nothing to repeat - Stack Overflow

programmeradmin0浏览0评论

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 0
Add a ment  | 

3 Answers 3

Reset to default 3

The 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. ;)

发布评论

评论列表(0)

  1. 暂无评论