Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java String remove all non numeric characters but keep the decimal separator

People also ask

How do I remove non numeric characters from a string?

In order to remove all non-numeric characters from a string, replace() function is used. replace() Function: This function searches a string for a specific value, or a RegExp, and returns a new string where the replacement is done.

How do you remove all but numbers from a string in Java?

You can make use of the ^ . It considers everything apart from what you have infront of it. String value = string. replaceAll("[^0-9]","");


Try this code:

String str = "a12.334tyz.78x";
str = str.replaceAll("[^\\d.]", "");

Now str will contain "12.334.78".


I would use a regex.

String text = "-jaskdh2367sd.27askjdfh23";
String digits = text.replaceAll("[^0-9.]", "");
System.out.println(digits);

prints

2367.2723

You might like to keep - as well for negative numbers.


Solution

With dash

String phoneNumberstr = "Tel: 00971-557890-999";
String numberRefined = phoneNumberstr.replaceAll("[^\\d-]", "");

Result: 0097-557890-999.

Without dash

If you also do not need "-" in String you can do like this:

String phoneNumberstr = "Tel: 00971-55 7890 999";      
String numberRefined = phoneNumberstr.replaceAll("[^0-9]", "");

Result: 0097557890999.


With guava:

String input = "abx123.5";
String result = CharMatcher.inRange('0', '9').or(CharMatcher.is('.')).retainFrom(input);

see http://code.google.com/p/guava-libraries/wiki/StringsExplained


str = str.replaceAll("\\D+","");