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?
10 Answers
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
Simple way without using Regex:
Adding an extra character check for dot '.' will solve the requirement:
public static String getOnlyNumerics(String str) {
if (str == null) {
return null;
}
StringBuffer strBuff = new StringBuffer();
char c;
for (int i = 0; i < str.length() ; i++) {
c = str.charAt(i);
if (Character.isDigit(c) || c == '.') {
strBuff.append(c);
}
}
return strBuff.toString();
}
Currency decimal separator can be different from Locale to another. It could be dangerous to consider . as separator always.
i.e.
╔════════════════╦═══════════════════╗
║ Locale ║ Sample ║
╠════════════════╬═══════════════════╣
║ USA ║ $1,222,333.44 USD ║
║ United Kingdom ║ £1.222.333,44 GBP ║
║ European ║ €1.333.333,44 EUR ║
╚════════════════╩═══════════════════╝
I think the proper way is:
- Get decimal character via
DecimalFormatSymbolsby default Locale or specified one. - Cook regex pattern with decimal character in order to obtain digits only
And here how I am solving it:
code:
import java.text.DecimalFormatSymbols;
import java.util.Locale;
public static String getDigit(String quote, Locale locale) {
char decimalSeparator;
if (locale == null) {
decimalSeparator = new DecimalFormatSymbols().getDecimalSeparator();
} else {
decimalSeparator = new DecimalFormatSymbols(locale).getDecimalSeparator();
}
String regex = "[^0-9" + decimalSeparator + "]";
String valueOnlyDigit = quote.replaceAll(regex, "");
try {
return valueOnlyDigit;
} catch (ArithmeticException | NumberFormatException e) {
Log.e(TAG, "Error in getMoneyAsDecimal", e);
return null;
}
return null;
}
I hope that may help,'.
A way to replace it with a java 8 stream:
public static void main(String[] args) throws IOException
{
String test = "ab19198zxncvl1308j10923.";
StringBuilder result = new StringBuilder();
test.chars().mapToObj( i-> (char)i ).filter( c -> Character.isDigit(c) || c == '.' ).forEach( c -> result.append(c) );
System.out.println( result ); //returns 19198.130810923.
}
This handles null inputs, negative numbers and decimals (you need to include the Apache Commons Lang library, version 3.8 or higher, in your project):
import org.apache.commons.lang3.RegExUtils;
result = RegExUtils.removeAll(input, "-?[^\\d.]");
Library reference: https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/RegExUtils.html