【发布时间】: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