298

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?

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
DRing
  • 6,825
  • 6
  • 29
  • 45
  • 5
    [myStr = myStr.replaceAll( "\[^\\d\]", "" )][1] [1]: http://stackoverflow.com/questions/1533659/how-do-i-remove-the-non-numeric-character-from-a-string-in-java – Bitmap Apr 29 '12 at 14:30
  • 2
    This is a strange way to say this. Isn't "all letters and characters that are not 0-9 and a period" equivalent to simpler "all characters that are not 0-9 and a period"? I mean, letters are characters which are not 0-9 nor the period. – Adam Zalcman Apr 29 '12 at 14:30

11 Answers11

612

Try this code:

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

Now str will contain "12.334.78".

Andriy M
  • 76,112
  • 17
  • 94
  • 154
Óscar López
  • 232,561
  • 37
  • 312
  • 386
122

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.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
70

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.

Fakhar
  • 3,946
  • 39
  • 35
23

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

Kerem Baydoğan
  • 10,475
  • 1
  • 43
  • 50
  • @egorikem if your project is already using guava, you can use it at no extra cost.. – stan Feb 19 '19 at 16:04
23
str = str.replaceAll("\\D+","");
Robert
  • 10,403
  • 14
  • 67
  • 117
Angoranator777
  • 334
  • 2
  • 6
  • Dunno why people downvoted your solution... Helped me alot, thanks! Votes up! – Zarial Apr 10 '17 at 10:34
  • Thanks Zarial, I see Robert actually edited my answer from str = str.replaceAll("\D+",""); to str = str.replaceAll("\\D+",""); ... So i made this mistake when pasting it into StackO's editor box thingy. So thank you Robert for fixing. Now it works! – Angoranator777 Oct 19 '17 at 23:26
  • it's downvoted cause it's a repost. Exact same answer has already been sublitted 5 years ago !! see above : https://stackoverflow.com/a/10372905/704246 – Saad Benbouzid Dec 13 '17 at 15:50
  • @SaadBenbouzid huh? what is your definition of the exact same answer? – Boris Treukhov Jan 31 '18 at 16:36
  • @BorisTreukhov see comment from "yeaaaahhhh..hamf hamf" from "Jan 26 '15 at 14:39" on the same page – Saad Benbouzid Jan 31 '18 at 17:03
  • 4
    @SaadBenbouzid 1) that is comment and not an answer 2) that is a completely different regex 3) not all answers which use regex D are identical it's like pointing that all C language answers which use `printf()` are duplicates. Also if you see an answer in comment you can ask mod to convert it to an answer or even add an answer on your own - answers in comments are discouraged on StackOverlow. – Boris Treukhov Jan 31 '18 at 17:20
10

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();
}
Shridutt Kothari
  • 7,326
  • 3
  • 41
  • 61
  • 1
    Since the `StringBuffer` is only being used inside the function, and not shared between threads, it would be recommended, for performance reasons, to use `StringBuilder`, instead. See: https://stackoverflow.com/a/4793503/679240 and https://stackoverflow.com/a/2771852/679240 – Haroldo_OK Feb 24 '22 at 12:35
6

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

Maher Abuthraa
  • 17,493
  • 11
  • 81
  • 103
6

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

Michael
  • 9,639
  • 3
  • 64
  • 69
3

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.
}
Orin
  • 920
  • 5
  • 16
2

The below code should remove all non-digit characters and allow periods.

String newString = currentString.replaceAll("[\\D.]", ""); 
David K
  • 73
  • 4
1

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

Yury
  • 722
  • 7
  • 14