Remove parentheses, dashes, and spaces from phone number

风流意气都作罢 提交于 2019-12-05 00:11:34

问题


I have a phone number like (123) 456-7890. I am using the replaceAll method to remove () and - and spaces from the string. I tried following

String phNo= "(123) 456-7890".replaceAll("[()-\\s]").trim();

but it's not working. Any solution?


回答1:


This should work:

String phNo = "(123) 456-7890".replaceAll("[()\\s-]+", "");

In your regex:

  • \s should be \\s
  • Hyphen should be first or last in character class to avoid escaping or use it as \\-
  • Use quantifier + as in [()\\s-]+ to increase efficiency by minimizing # of replacements



回答2:


If you want the phone number then use:

String phNo = "(123) 456-7890".replaceAll("\\D+", "");

This regex will mark all characters that are not digits, and replace them with an empty string.


The regex: \D+

  • Match a single character that is not a digit. \D
    • Between one and unlimited times, as many times as possible. +



回答3:


The - character with brackets [] indicates a character range, e.g. [a-z]. However, the character range doesn't work here where you want a literal - to be used. Escape it.

String phNo = "(123) 456-7890".replaceAll("[()\\-\\s]", "").trim());



回答4:


  String newStr = phoneNumber.replaceAll("[^0-9]", "");
        System.out.println(newStr);

Removes All Non-Digit Characters.

Java Regex - Tutorial




回答5:


There are two main reasons this does not work as expected.

  1. Inside of a character class the hyphen has special meaning. You can place a hyphen as the first or last character of the class. In some regular expression implementations, you can also place directly after a range. If you place the hyphen anywhere else you need to escape it in order to add it to your class.

    String phNo = "(123) 456-7890".replaceAll("[()\\-\\s]").trim();
                                                  ^^
    
  2. You are not supplying a replacement value which neither answer has pointed out to you.

    String phNo = "(123) 456-7890".replaceAll("[()\\-\\s]", "").trim();
                                                            ^^
    

    And finally, you can remove .trim() here as well.

    String phNo = "(123) 456-7890".replaceAll("[()\\-\\s]", "");
    



回答6:


If you are using Kotlin than

mobileNo.replace(Regex("[()\\-\\s]"), "")



来源:https://stackoverflow.com/questions/25089362/remove-parentheses-dashes-and-spaces-from-phone-number

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!