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 error unclosed group
.
You can remove everything but the digits:
phone = phone.replaceAll("[^0-9]","");
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 uses Pattern.LITERAL
flag inside regex compiler to point that metacharacters used in regex are simple literals without any special meaningIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With