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

Trying to remove all letters and characters that are not 0-9 and a period. I'm using Character.isDigit() but it also removes decimal, how can I also keep the decimal?


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