正则表达式允许电话号码与国家代码

时间:2015-04-12 07:12:44

标签: javascript c# regex

我需要一个正则表达式来验证电话号码(使用国家/地区代码),该电话号码应遵循以下条件

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

E.g

    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-012345      - Fail (3rd Condition fails)
    7 - +91-12345678910 - Fail (4th condition fails)

请帮帮我。谢谢。

2 个答案:

答案 0 :(得分:1)

\+\d{1,4}-(?!0)\d{1,10}\b

细分:

\+                        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-012345',
    '+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]) + ', ';
}
&#13;
<p id="result"></p>
&#13;
&#13;
&#13;

答案 1 :(得分: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-012345") == 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