代码之家  ›  专栏  ›  技术社区  ›  Shawn Miller

电话号码格式,OnBlur

  •  0
  • Shawn Miller  · 技术社区  · 17 年前

    我有一个用于电话号码字段的.NETWinForms文本框。在允许自由格式文本后,我希望在用户离开文本框后将文本格式化为“更可读”的电话号码。(当您创建/编辑联系人时,Outlook为电话字段提供了此功能)

    • 1234567890变为(123)456-7890
    • (123)456.7890变为(123)456-7890
    • 123.4567x123变为123-4567x123
    7 回复  |  直到 17 年前
        1
  •  2
  •   brock.holum    17 年前

    一个相当简单的方法是使用正则表达式。根据您接受的电话号码类型,您可以编写一个正则表达式来查找数字(仅对我们而言,您知道总共可能有7个或10个-可能带有前导的“1”)以及它们之间的潜在分隔符(句点、破折号、parens、空格等)。

    Regex regex = new Regex(@"(?<areaCode>([\d]{3}))?[\s.-]?(?<leadingThree>([\d]{3}))[\s.-]?(?<lastFour>([\d]{4}))[x]?(?<extension>[\d]{1,})?");
    string phoneNumber = "701 123-4567x324";
    
    Match phoneNumberMatch = regex.Match(phoneNumber);
    if(phoneNumberMatch.Success)
    {
       if (phoneNumberMatch.Groups["areaCode"].Success)
       {
          Console.WriteLine(phoneNumberMatch.Groups["areaCode"].Value);
       }
       if (phoneNumberMatch.Groups["leadingThree"].Success)
       {
          Console.WriteLine(phoneNumberMatch.Groups["leadingThree"].Value);
       }
       if (phoneNumberMatch.Groups["lastFour"].Success)
       {
          Console.WriteLine(phoneNumberMatch.Groups["lastFour"].Value);
       }
       if (phoneNumberMatch.Groups["extension"].Success)
       {
          Console.WriteLine(phoneNumberMatch.Groups["extension"].Value);
       }
    }
    
        2
  •  1
  •   Community Mohan Dere    9 年前

    我认为最简单的方法是首先从字符串中去掉任何非数字字符,这样您就只需要一个数字,然后就可以使用本文中提到的格式 question

        3
  •  1
  •   Shawn Miller    17 年前

    我考虑过去掉任何非数字字符,然后格式化,但我不认为这对扩展大小写(123.4567x123)有效

        4
  •  1
  •   Dennis Williamson    17 年前

    Start: 123.4567x123
    Lop: 123.4567
    Strip: 1234567
    Format: 123-4567
    Add: 123-4567 x123
    
        5
  •  0
  •   Davy8    17 年前

    除了自己做,我不知道其他的方法,可能做一些面具,检查哪一个匹配,并根据具体情况做每个面具。别以为这太难了,只是很费时。

        6
  •  0
  •   Mitchel Sellers    17 年前

    我的猜测是,您可以使用一个条件语句来查看输入,然后将其解析为特定的格式。但我猜会有大量的逻辑来研究输入和格式化输出。

        7
  •  0
  •   dividius    16 年前

    public static string FormatPhoneNumber(string phone)
    {
        phone = Regex.Replace(phone, @"[^\d]", "");
        if (phone.Length == 10)
            return Regex.Replace(phone,
                                 "(?<ac>\\d{3})(?<pref>\\d{3})(?<num>\\d{4})",
                                 "(${ac}) ${pref}-${num}");
        else if ((phone.Length < 16) && (phone.Length > 10))
            return Regex.Replace(phone,
                                 "(?<ac>\\d{3})(?<pref>\\d{3})(?<num>\\d{4})(?<ext>\\d{1,5})", 
                                 "(${ac}) ${pref}-${num} x${ext}");
        else
            return string.Empty;
    

    }

    推荐文章