user3786942
user3786942

Reputation: 163

Remove parentheses, dashes, and spaces from phone number

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?

Upvotes: 9

Views: 32099

Answers (7)

KingJoeffrey
KingJoeffrey

Reputation: 391

IN 2022 use this! all other answers too old!!!!!!!!!!!

result = "(123) 456-7890".replace(/[^+\d]+/g, "");

Upvotes: 5

Mohit Suthar
Mohit Suthar

Reputation: 9395

If you are using Kotlin than

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

Upvotes: 1

katwal-dipak
katwal-dipak

Reputation: 3691

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

Removes All Non-Digit Characters.

Java Regex - Tutorial

Upvotes: 4

Andie2302
Andie2302

Reputation: 4897

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

Upvotes: 5

hwnd
hwnd

Reputation: 70750

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

Upvotes: 2

rgettman
rgettman

Reputation: 178333

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

Upvotes: 3

anubhava
anubhava

Reputation: 786091

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

Upvotes: 22

Related Questions