Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove spaces and special characters from string

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.

like image 716
Mike Avatar asked Nov 27 '22 03:11

Mike


2 Answers

You can remove everything but the digits:

phone = phone.replaceAll("[^0-9]","");
like image 97
jcaron Avatar answered Nov 30 '22 22:11

jcaron


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 meaning
like image 32
Pshemo Avatar answered Nov 30 '22 23:11

Pshemo