Java 从电话号码中删除dash

Java 从电话号码中删除dash,java,regex,phone-number,Java,Regex,Phone Number,使用java的什么正则表达式可以用来从表示电话号码的字符串中过滤掉破折号“-”并打开闭合圆括号 所以(234)887-9999应该给出2348879999 同样地,234-887-9999应该给出2348879999 谢谢 phoneNumber.replaceAll("[\\s\\-()]", ""); 正则表达式定义了一个字符类,该类由任何空白字符(\s,由于我们在传递字符串,所以将其转义为\\s)、破折号(转义是因为破折号在字符类的上下文中表示特殊的内容)和括号组成 看 编辑 Per:

使用java的什么正则表达式可以用来从表示电话号码的字符串中过滤掉破折号“-”并打开闭合圆括号

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

谢谢

phoneNumber.replaceAll("[\\s\\-()]", "");
正则表达式定义了一个字符类,该类由任何空白字符(
\s
,由于我们在传递字符串,所以将其转义为
\\s
)、破折号(转义是因为破折号在字符类的上下文中表示特殊的内容)和括号组成

编辑

Per:


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

最好只选择
“\\D”
。它更直接地表达了原意。“删除任何不是数字的东西。”以上两种方法都适用于我的情况。。。因为我限制用户只输入数字、圆括号和破折号。。。谢谢大家:)大家好!如果我想在字符串中保留+并删除所有其他字符,该怎么办?@ShajeelAfzal指出电话号码可以包含
+
phoneNumber.replaceAll(“\\D”,”)
建议不够保守。
    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;

    }
    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;

    }