从电话号码中删除短划线

zoo*_*277 27 java regex phone-number

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

所以(234)887-9999应该给2348879999,类似地234-887-9999应该给2348879999.

谢谢,

Viv*_*ath 66

phoneNumber.replaceAll("[\\s\\-()]", "");
Run Code Online (Sandbox Code Playgroud)

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

String.replaceAll(String, String).

编辑

Per gunslinger47:

phoneNumber.replaceAll("\\D", "");
Run Code Online (Sandbox Code Playgroud)

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

  • 可能最好去"\\ D"`.它更直接地说出了初​​衷."删除任何不是数字的东西." (12认同)

Tha*_*nda 7

    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;

    }
Run Code Online (Sandbox Code Playgroud)