【问题标题】:c# Regex to match all Sri Lankan phone numbersc# Regex 匹配所有斯里兰卡电话号码
【发布时间】:2019-01-02 09:49:29
【问题描述】:

我在 google 上没有找到关于 斯里兰卡电话号码正则表达式; 格式为:

  1. 7756456459 位)
  2. 077564564510 位)
  3. +94775645645

它应该以 70+94 开头。谁能帮我这个。 感谢您的解决方案。

【问题讨论】:

标签: c# regex validation


【解决方案1】:

让我们构建pattern

 ^            - anchor (string start)
 7|0|(?:\+94) - either 7 or 0 or +94
[0-9]{9,10}   - from 9 up and including to 10 digits (chars on [0-9] range)
 $            - anchor (string end)

所以我们有

  string pattern = @"^(?:7|0|(?:\+94))[0-9]{9,10}$";

测试:

string[] tests = new string[] {
  "775645645",
  "0775645645",
  "+94775645645",
  "123456669",
  "1234566698888",
  "+941234566698888",
  "+94123456"
};

string pattern = @"^(?:7|0|(?:\+94))[0-9]{9,10}$";

string report = string.Join(Environment.NewLine, tests
  .Select(item => $"{item,-20} : {(Regex.IsMatch(item, pattern) ? "Matched" : "Not")}"));

Console.Write(report);

结果:

775645645            : Matched
0775645645           : Matched
+94775645645         : Matched
123456669            : Not
1234566698888        : Not
+941234566698888     : Not
+94123456            : Not

【讨论】:

  • 我尝试将其用于角度 +94775645645 这给了我不匹配的状态。如果我减去一个数字,它显示为有效。我认为语言无关紧要正则表达式对于每个软件都是一样的,对吗?这是我的代码“Validators.pattern('^7|0|(?:\\+94)[0-9]{9,10}$')”
  • @Sahan Pasindu Nirmal:请把 comment 变成 question 好吗?用 Angular 标签标记它,不仅提供Validators.pattern('^7|0|(?:\\+94)[0-9]{9,10}$'),还提供上下文(如何在输入数据上应用验证器)?
  • 在角度中,我们可以使用这种方法“Validators.pattern”指定模式验证,完整代码如下 this.registrationForm = this.fb.group({ userName: [ null, Validators.compose([Validators. maxLength(30), Validators.pattern('[a-zA-Z ]*'), Validators.required]) ],
  • 你错过了整个正则表达式的括号,因为它匹配任何以7开头的字符串或任何包含0的字符串,请参阅:regex101.com/r/osHPJF/1
  • @Toto:我明白了,不错的收获!谢谢!
【解决方案2】:
 String regexPhoneNumber = "^(?:0|94|\\+94)?(?:(11|21|23|24|25|26|27|31|32|33|34|35|36|37|38|41|45|47|51|52|54|55|57|63|65|66|67|81|912)(0|2|3|4|5|7|9)|7(0|1|2|5|6|7|8)\\d)\\d{6}$";

有效电话号码类型:-

  • 0771234567

  • 771234567

  • +94771234567

  • 94771234567

  • 0111234567(本地代码)

【讨论】:

  • 你应该使用字符类而不是这些长的交替,例如[0-25-8]而不是(0|1|2|5|6|7|8)
【解决方案3】:

更新到新分配的移动提供商:

String regexPhoneNumber = "^(?:0|94|\\+94)?(?:(11|21|23|24|25|26|27|31|32|33|34|35|36|37|38|41|45|47|51|52|54|55|57|63|65|66|67|81|912)(0|2|3|4|5|7|9)|7(0|1|2|4|5|6|7|8)\\d)\\d{6}$";

【讨论】:

    猜你喜欢
    • 2012-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多