Remove spaces and special characters from string
Solution 1
You can remove everything but the digits:
phone = phone.replaceAll("[^0-9]","");
Solution 2
To remove all non-digit characters you can use
replaceAll("\\D+",""); \\ \D is negation of \d (where \d represents digit)
If you want to remove only spaces, (
and )
you can define your own character class like
replaceAll("[\\s()]+","");
Anyway your problem was caused by fact that some of characters in regex are special. Among them there is (
which can represent for instance start of the group. Similarly )
can represent end of the group.
To make such special characters literals you need to escape them. You can do it many ways
-
"\\("
- standard escaping in regex -
"[(]"
- escaping using character class -
"\\Q(\\E"
-\Q
and\E
create quote - which means that regex metacharacters in this area should be treated as simple literals -
Pattern.quote("("))
- this method usesPattern.LITERAL
flag inside regex compiler to point that metacharacters used in regex are simple literals without any special meaning
Solution 3
You need to escape the (
as it denotes a metacharacter (start of a group) in regular expressions. Same for )
.
phone = phone.replaceAll("\\(","");
Mike
Updated on June 25, 2022Comments
-
Mike almost 2 years
How can I format a string phone number to remove special characters and spaces?
The number is formatted like this (123) 123 1111
I am trying to make it look like this: 1231231111
So far I have this:
phone = phone.replaceAll("\\s",""); phone = phone.replaceAll("(","");
The first line will remove the spaces. Then I am having trouble removing the parentheses. Android studio underlines the
"("
and throws the errorunclosed group
.