从电话号码中删除短划线

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

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

谢谢,

phoneNumber.replaceAll("[\\s\\-()]", ""); 

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

请参见String.replaceAll(String, String)

编辑

Per gunslinger47 :

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