2015-04-12 53 views
-4

我需要一個正則表達式來驗證電話號碼(含國家代碼),它應當遵循以下條件正則表達式,以便與國家代碼******中國

1 - There should be at max 4 digits in between + and - . 
2 - Phone number shall be a combination of +,- and digits 
3 - 0 shall not be allowed after - 
4 - After - only 10 digits are allowed 

1 - +91234-1234567 - Fail (1st Condition fails) 
    2 - +9123-1234567 - Pass 
    3 - +    - Fail (2nd condition fails) 
    4 - -    - Fail (2nd condition fails) 
    5 - 91234545555  - Fail (2nd condition fails) 
    6 - +91-- Fail (3rd Condition fails) 
    7 - +91-12345678910 - Fail (4th condition fails) 

請幫我在這。提前致謝。

回答

1

擊穿:

\+      Match a literal + 
\d{1,4}     Match between 1 and 4 digits inclusive 
-       Match a literal - 
(?!      Negative lookahead, fail if 
    0      this token (literal 0) is found 
) 
\d{1,10}     Match between 1 and 10 digits inclusive 
\b      Match a word boundary 

演示(與你的例子)

var phoneRegexp = /\+\d{1,4}-(?!0)\d{1,10}\b/g, 
 
    tests = [ 
 
    '+91234-1234567', 
 
    '+9123-1234567', 
 
    '+', 
 
    '-', 
 
    '91234545555', 
 
    '+91-', 
 
    '+91-12345678910' 
 
    ], 
 
    results = [], 
 
    expected = [false, true, false, false, false, false, false]; 
 

 
results = tests.map(function(el) { 
 
    return phoneRegexp.test(el); 
 
}); 
 

 
for (var i = 0; i < results.length; i++) { 
 
    document.getElementById('result').textContent += (results[i] === expected[i]) + ', '; 
 
}
<p id="result"></p>

+0

沒有產生超越知識正則表達式和學習,我知道的一個工具。對於大多數正則表達式,我通常會找到一個衆所周知的,經過良好測試的正則表達式來匹配已知格式。 – jdphenix

+0

使用超前而不是'\ + \ d {1,4} - [1-9] \ d {,9} \ b'有沒有好處? –

+0

@vivek試試看,不明白爲什麼不。 – jdphenix

1

在C#中,你可以去:

public class RegexTelephoneNumber 
{ 
    public void Test() 
    { 
     Regex regex = new Regex(@"^\+\d{1,4}-[1-9]\d{0,9}$"); 

     Trace.Assert(MatchTest(regex, "+91234-1234567") == false); 
     Trace.Assert(MatchTest(regex, "+9123-1234567") == true); 
     Trace.Assert(MatchTest(regex, "+") == false); 
     Trace.Assert(MatchTest(regex, "-") == false); 
     Trace.Assert(MatchTest(regex, "91234545555") == false); 
     Trace.Assert(MatchTest(regex, "+91-") == false); 
     Trace.Assert(MatchTest(regex, "+91-12345678910") == false); 

     Trace.Assert(MatchTest(regex, "++91234-1234567") == false); 
     Trace.Assert(MatchTest(regex, "+91234-1234567+") == false); 
     Trace.Assert(MatchTest(regex, "aa+91234-1234567+bb") == false); 
     Trace.Assert(MatchTest(regex, "+91-12") == true); 
    } 

    private bool MatchTest(Regex regex, string text) 
    { 
     Match match = regex.Match(text); 
     return match.Success; 
    } 
} 

正則表達式解釋說:

^  - start anchor 
\+  - character '+' 
\d{1,4) - any digit repeating min 1 and max 4 times 
-  - character '-' 
[1-9] - any digit apart from 0, taking place exactly once 
\d{0,9} - any digit repeating min 0 and max 9 times 
$  - end anchor