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?


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


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. +


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());


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

Removes All Non-Digit Characters.

Java Regex - Tutorial


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]", "");


If you are using Kotlin than

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