带有可选CountryCode的phoneNumber的RegEx

时间:2015-04-28 06:48:49

标签: javascript regex

我使用 pr1 = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()),true); ServerSocket serversocket = new ServerSocket(5000); socket = serversocket.accept(); 执行以下测试用例

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

E.g

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
5 - Space allowed after and before -

现在我想将一些部分(国家代码+ 91-)作为可选项来执行以下测试用例

    1 - +91234-1234567 - Fail (1st Condition fails)
    2 - +123-1234567  - Pass 
    3 - +               - Fail (2nd condition fails)
    4 - -               - Fail (2nd condition fails)
    5 - 91234545555     - Fail (2nd condition fails)
    6 - +21-012345      - Fail (3rd Condition fails)
    7 - +91-12345678910 - Fail (4th condition fails)
    8 - +32 - 12345678  - Pass (Space allowed before and after -)

为了实现这一点,我在正则表达式E.g. 1)12345678 - Pass (Since we are making country code(+91-) as optional) 2)+1233433 - Fail 3)+91-1233333- pass 中进行了以下更改,但是使用上面更新的正则表达式,它还允许以下内容

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

我想将整个事情视为可选(+ XX-),而不是它的一部分。 请帮帮我。提前谢谢。

1 个答案:

答案 0 :(得分:1)

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

细分:

^                                  Assert at beginning of string 
(?:\+\d{1,4}\s?-\s?)?              Only changed to group country code
                                   and make it match 0 - 1 times.
and the rest                       Otherwise no changes. 

密钥更改是字符串边界断言和可选的国家/地区代码组。