Reputation: 163
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
Reputation: 391
IN 2022 use this! all other answers too old!!!!!!!!!!!
result = "(123) 456-7890".replace(/[^+\d]+/g, "");
Upvotes: 5
Reputation: 9395
If you are using Kotlin than
mobileNo.replace(Regex("[()\\-\\s]"), "")
Upvotes: 1
Reputation: 3691
String newStr = phoneNumber.replaceAll("[^0-9]", "");
System.out.println(newStr);
Removes All Non-Digit Characters.
Upvotes: 4
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+
\D
+
Upvotes: 5
Reputation: 70750
There are two main reasons this does not work as expected.
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();
^^
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
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
Reputation: 786091
This should work:
String phNo = "(123) 456-7890".replaceAll("[()\\s-]+", "");
In your regex:
\s
should be \\s
\\-
+
as in [()\\s-]+
to increase efficiency by minimizing # of replacementsUpvotes: 22