【问题标题】:Formatting a Phone number [duplicate]格式化电话号码[重复]
【发布时间】:2014-05-08 15:07:38
【问题描述】:

如何将电话号码从 (###)###-#### 格式化为 ##########?有没有最好的方法来做到这一点?我可以使用String.Substring 来获取每个数字块,然后将它们连接起来。但是,还有其他复杂的方法吗?

【问题讨论】:

    标签: c# regex formatting phone-number


    【解决方案1】:

    简单的正则表达式替换怎么样?

    string formatted = Regex.Replace(phoneNumberString, "[^0-9]", "");
    

    这实际上只是一个数字白名单。看到这个小提琴:http://dotnetfiddle.net/ssdWSd

    输入:(123) 456-7890

    输出:1234567890

    【讨论】:

    • + 是不必要的,因为该函数将查找所有满足指定正则表达式的子字符串并替换它。
    • @wei2912 你是对的,固定的。
    【解决方案2】:

    我会使用 LINQ:

    var result = new String(phoneString.Where(x => Char.IsDigit(x)).ToArray());
    

    虽然正则表达式也有效,但这不需要任何特殊设置。

    【讨论】:

      【解决方案3】:

      一个简单的方法是:

      myString = myString.Replace("(", "");
      myString = myString.Replace(")", "");
      myString = myString.Replace("-", "");
      

      用空字符串替换每个字符。

      【讨论】:

      • 这行不通,因为它假定字符串是可变的,而事实并非如此。
      • 我总是忘记这一点。我的编辑有效吗?
      • 现在可以了。 -1 不是我写的。
      • 这很酷。早点错了,估计是谁都回不来了。我不敢相信我多久忘记字符串在 c# 中是不可变的。有时我需要 15 分钟的调试时间才能发现它。
      【解决方案4】:

      试试这个:

      resultString = Regex.Replace(subjectString, @"^\((\d+)\)(\d+)-(\d+)$", "$1$2$3");
      

      正则表达式解释

      ^\((\d+)\)(\d+)-(\d+)$
      
      Assert position at the beginning of the string «^»
      Match the character “(” literally «\(»
      Match the regex below and capture its match into backreference number 1 «(\d+)»
         Match a single character that is a “digit” (0–9 in any Unicode script) «\d+»
            Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
      Match the character “)” literally «\)»
      Match the regex below and capture its match into backreference number 2 «(\d+)»
         Match a single character that is a “digit” (0–9 in any Unicode script) «\d+»
            Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
      Match the character “-” literally «-»
      Match the regex below and capture its match into backreference number 3 «(\d+)»
         Match a single character that is a “digit” (0–9 in any Unicode script) «\d+»
            Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
      Assert position at the end of the string, or before the line break at the end of the string, if any (line feed) «$»
      
      $1$2$3
      
      Insert the text that was last matched by capturing group number 1 «$1»
      Insert the text that was last matched by capturing group number 2 «$2»
      Insert the text that was last matched by capturing group number 3 «$3»
      

      【讨论】:

      • 愿意解释否决票吗?
      猜你喜欢
      • 1970-01-01
      • 2018-09-08
      • 2020-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多