【问题标题】:RegEx for phoneNumber with optional CountryCode带有可选国家代码的电话号码的正则表达式
【发布时间】:2015-04-28 06:48:48
【问题描述】:

我正在使用\+\d{1,4}\s?-\s?(?!0)\d{1,10}\b 执行以下测试用例

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 -

例如

    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 -)

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

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/ 中进行了以下更改,但使用上述更新的正则表达式,它也允许以下更改

     1)-123455
     2)+123333

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

【问题讨论】:

  • 我觉得我以前回答过这个问题......
  • @jdphenix。是的,您已经回答了,但现在需要进行更多更改,如前所述(将国家/地区代码设为可选)。请帮助我实现同样的目标。
  • @vivek:这样的事情会不会:regex101.com/r/xN5pQ9/1?不要将整个第一部分设为可选,而是为+91 添加一个替代项:(?:-\s*\+91\s*-|\+\d{1,4}\s?-\s?)
  • @stribizhev 我用你给出的正则表达式试过这个,但它失败了。 var phoneReg = new RegExp(/(?:-\s*\+91\s*-|\+\d{1,4}\s?-\s?)/); phoneReg.test("12");无论如何,它不仅是 +91 。它可以是任何数字。
  • @vivek:您针对我的正则表达式的一部分进行了测试。此外,您正在使用 RegExp 构造函数表示法,然后,您需要使用双斜杠(完整的 JS RegExp 声明代码 var phoneReg = new RegExp("(?:-\\s*\\+\\d{2}\\s*-|\\+\\d{1,4}\\s?-\\s?)(?!0)\\d{1,10}\\b");)。在此处查看另一个演示:jsfiddle.net/mrxafevc

标签: javascript regex


【解决方案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. 

主要变化是字符串边界断言和可选的国家代码组。

【讨论】:

  • 如果电话号码字符串出现在更大的字符串中怎么办?
  • 我从stackoverflow.com/questions/29586983/… 的先前交互中假设这不是问题。显然,这不会匹配字符串中的电话号码。
  • @jdphenix 谢谢 .. 它不会有更大的字符串。但以上对“\91123”和“1-91123”返回真。如果 - 存在,则 + 应该存在,反之亦然。你能相应地更新正则表达式吗?
猜你喜欢
  • 1970-01-01
  • 2020-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-10
  • 2012-10-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多