Reputation: 7039
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?
Upvotes: 303
Views: 435867
Reputation: 103
The below code should remove all non-digit characters and allow periods.
String newString = currentString.replaceAll("[\\D.]", "");
Upvotes: 3
Reputation: 4069
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
.
Upvotes: 73
Reputation: 17813
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:
DecimalFormatSymbols
by default Locale or
specified one.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,'.
Upvotes: 6
Reputation: 781
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
Upvotes: 1
Reputation: 9864
For the Android folks coming here for Kotlin
val dirtyString = "💰 Account Balance: $-12,345.67"
val cleanString = dirtyString.replace("[^\\d.]".toRegex(), "")
Output:
cleanString = "12345.67"
This could then be safely converted toDouble()
, toFloat()
or toInt()
if needed
Upvotes: 6
Reputation: 930
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.
}
Upvotes: 3
Reputation: 7394
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();
}
Upvotes: 10
Reputation:
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
Upvotes: 23
Reputation: 236004
Try this code:
String str = "a12.334tyz.78x";
str = str.replaceAll("[^\\d.]", "");
Now str
will contain "12.334.78"
.
Upvotes: 621
Reputation: 533500
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.
Upvotes: 125