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.
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.
String phoneNumberstr = "Tel: 00971-557890-999";
String numberRefined = phoneNumberstr.replaceAll("[^\\d-]", "");
Result: 0097-557890-999
.
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+","");
If 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