Javascript Regex允许使用带有国家代码的电话号码
我需要一个正则表达式来验证符合以下条件的电话号码(带有国家代码)Javascript Regex允许使用带有国家代码的电话号码,javascript,c#,regex,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 例如 请在这方面帮助我。提前谢谢 \+\d{1,4
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
例如
请在这方面帮助我。提前谢谢
\+\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,
测试=[
'+91234-1234567',
'+9123-1234567',
'+',
'-',
'91234545555',
'+91-012345',
'+91-12345678910'
],
结果=[],
预期=[假,真,假,假,假,假,假];
结果=测试。映射(功能(el){
返回phoneRegexp.test(el);
});
对于(var i=0;i
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;
}
}
Regex解释说:
^ - 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
据我所知,没有一种工具可以生成超出知识和学习范围的正则表达式。对于大多数正则表达式,我通常会找到一个众所周知的、经过良好测试的正则表达式来匹配已知的格式。使用前瞻而不是\+\d{1,4}-[1-9]\d{,9}\b
?@vivek试一试,看一看,不知道为什么。@zoharpeld我怀疑\+\d{1,4}-[1-9]\d{1,9}\b
执行得更快。我使用了lookahead,因为它更接近于要求的语义“0不应在以下情况下被允许——
^ - 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