【问题标题】:Remove dash from a phone number从电话号码中删除破折号
【发布时间】:2011-02-12 15:07:35
【问题描述】:

使用 java 的正则表达式可用于过滤掉破折号 '-' 并从代表电话号码的字符串中打开右圆括号...

所以 (234) 887-9999 应该给 2348879999 同样,234-887-9999 应该给出 2348879999。

谢谢,

【问题讨论】:

    标签: java regex phone-number


    【解决方案1】:
    phoneNumber.replaceAll("[\\s\\-()]", "");
    

    正则表达式定义了一个字符类,由任何空白字符(\s,转义为\\s,因为我们传入一个字符串),一个破折号(转义,因为破折号在上下文中意味着特殊的东西字符类)和括号。

    String.replaceAll(String, String)

    编辑

    gunslinger47

    phoneNumber.replaceAll("\\D", "");
    

    用空字符串替换任何非数字。

    【讨论】:

    • 最好选择"\\D"。更直接的说出了初衷。 “删除任何不是数字的东西。”
    • 以上两种方法都适用于我的情况......因为我限制用户只能输入数字,圆括号和破折号......非常感谢大家:)
    • 大家好!如果我想在字符串中保留 + 并删除所有其他字符怎么办?
    • @ShajeelAfzal 指出电话号码可以包含+phoneNumber.replaceAll("\\D", "") 的建议不够保守。
    【解决方案2】:
        public static String getMeMyNumber(String number, String countryCode)
        {    
             String out = number.replaceAll("[^0-9\\+]", "")        //remove all the non numbers (brackets dashes spaces etc.) except the + signs
                            .replaceAll("(^[1-9].+)", countryCode+"$1")         //if the number is starting with no zero and +, its a local number. prepend cc
                            .replaceAll("(.)(\\++)(.)", "$1$3")         //if there are left out +'s in the middle by mistake, remove them
                            .replaceAll("(^0{2}|^\\+)(.+)", "$2")       //make 00XXX... numbers and +XXXXX.. numbers into XXXX...
                            .replaceAll("^0([1-9])", countryCode+"$1");         //make 0XXXXXXX numbers into CCXXXXXXXX numbers
             return out;
    
        }
    

    【讨论】:

      【解决方案3】:

      我的 Kotlin 版本的工作解决方案 -(扩展功能)

      fun getMeMyNumber(number: String, countryCode: String): String? {
          return number.replace("[^0-9\\+]".toRegex(), "") //remove all the non numbers (brackets dashes spaces etc.) except the + signs
              .replace("(^[1-9].+)".toRegex(), "$countryCode$1") //if the number is starting with no zero and +, its a local number. prepend cc
              .replace("(.)(\\++)(.)".toRegex(), "$1$3") //if there are left out +'s in the middle by mistake, remove them
              .replace("(^0{2}|^\\+)(.+)".toRegex(), "$2") //make 00XXX... numbers and +XXXXX.. numbers into XXXX...
              .replace("^0([1-9])".toRegex(), "$countryCode$1") //make 0XXXXXXX numbers into CCXXXXXXXX numbers
      }
      

      【讨论】:

      • 请注意这个问题是关于 Java 的(即使 Kotlin 翻译不是那么难)它不适用于上下文。
      • @Leonardo 这个答案是针对 Kotlin 中的同一个问题,因为这将帮助其他人在 kotlin 而不是 java 中寻找确切的解决方案?
      猜你喜欢
      • 1970-01-01
      • 2022-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-29
      • 1970-01-01
      • 1970-01-01
      • 2013-06-03
      相关资源
      最近更新 更多