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

JavaStringCharacterDecimal

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

Try this code:

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

Now str will contain "12.334.78".

Solution 2 - Java

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 3 - Java

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.

Solution 4 - Java

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

Solution 5 - Java

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

Solution 6 - Java

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();
}

Solution 7 - Java

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 DecimalFormatSymbols by 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,'.

Solution 8 - Java

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

Solution 9 - Java

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.
}

Solution 10 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDRingView Question on Stackoverflow
Solution 1 - JavaÓscar LópezView Answer on Stackoverflow
Solution 2 - JavaPeter LawreyView Answer on Stackoverflow
Solution 3 - JavaFaakhirView Answer on Stackoverflow
Solution 4 - Javauser180100View Answer on Stackoverflow
Solution 5 - JavaAngoranator777View Answer on Stackoverflow
Solution 6 - JavaShridutt KothariView Answer on Stackoverflow
Solution 7 - JavaMaher AbuthraaView Answer on Stackoverflow
Solution 8 - JavaMichaelView Answer on Stackoverflow
Solution 9 - JavaOrinView Answer on Stackoverflow
Solution 10 - JavaYuryView Answer on Stackoverflow