2014-01-16 45 views
0

我的数据:(222)222-2222简单的电话号码的正则表达式不工作

这是为什么不及格?

checkRegexp(TelephoneNumber, /^(d{3}) d{3}-d{4}$/, "Please enter your 10 digit phone number."); 


function checkRegexp(o, regexp, n) { 
       if (!(regexp.test(o.val()))) { 
        o.addClass("ui-state-error"); 
        updateTips(n); 
        return false; 
       } else { 
        return true; 
       } 
      } 

回答

2

()是指捕获组正则表达式的特殊字符,你需要躲避他们的。您还希望有\d用于数字字符。如果没有\,则表示您匹配d

/^\(\d{3}\) \d{3}-\d{4}$/ 

当你有一个正则表达式的问题,你可以使用一个网站就像http://regex101.com/,包括正则表达式的解释。你会发现括号不被视为文字字符。

比如,你原来的正则表达式:

^ assert position at start of the string 
1st Capturing group (d{3}) 
d{3} matches the character d literally (case sensitive) 
Quantifier: Exactly 3 times 
    matches the character literally 
d{3} matches the character d literally (case sensitive) 
Quantifier: Exactly 3 times 
- matches the character - literally 
d{4} matches the character d literally (case sensitive) 
Quantifier: Exactly 4 times 
$ assert position at end of the string 

你会很容易看到的问题。

+0

谢谢你soooo和详细的解释! – Pinch