Javascript 带有可选国家代码的phoneNumber的正则表达式
我正在使用Javascript 带有可选国家代码的phoneNumber的正则表达式,javascript,regex,Javascript,Regex,我正在使用\+\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 allo
\+\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 -
E.g.
1)12345678 - Pass (Since we are making country code(+91-) as optional)
2)+1233433 - Fail
3)+91-1233333- pass
例如
现在我想让一些部分(国家代码+91-)作为可选部分来执行下面的测试用例
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 -
E.g.
1)12345678 - Pass (Since we are making country code(+91-) as optional)
2)+1233433 - Fail
3)+91-1233333- pass
为了实现这一点,我在regex/(\+\d{1,4}\s?-\s?)(?!0)\d{1,10}\b/
中做了以下更改,但使用上面更新的regex-its还允许
1)-123455
2)+123333
我想让整个事情成为可选(+XX-)而不是它的一部分。
请帮帮我。提前谢谢
/^(?:\+\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.
关键的更改是字符串边界断言和可选的国家/地区代码组 我觉得我以前已经回答过了…@jdpenix。是的,您已经回答了,但现在需要进行更多的更改(使国家代码可选)。请帮我实现同样的目标。@vivek:这样做行吗:?不是让整个第一部分都是可选的,而是为
+91
:(?:-\s*\+91\s*-\124+\ d{1,4}\s?-\s?
@Stribizev添加一个替代项。我用您给出的正则表达式尝试了这个方法,但失败了。var phoneReg=new RegExp(/(?:-\s*\+91\s*-\+\d{1,4}\s?-\s?/);电话注册测试(“12”);无论如何,它不仅是+91。它可以是任何数字。@vivek:你测试了我的正则表达式的一部分。另外,如果您使用的是RegExp构造函数表示法,则需要使用双斜杠(完整的JS RegeExp声明代码var phoneReg=new RegExp((?:-\\s*\\+\\d{2}\\s*-\\+\\d{1,4}\\s?-\\s?(!0)\\d{1,10}\\b”)
)。请参阅此处的另一个演示:如果电话号码字符串位于更大的字符串中,该怎么办?我从上一次的交互中假设这不是问题。显然,这与字符串中的电话号码不匹配。@jdpenix谢谢。。它不会以更大的字符串出现。但对于“\91123”和“1-91123”,上述结果为真。如果-存在,那么+应该存在,反之亦然。你能相应地更新正则表达式吗?