Extract digits from a string in Java

I have a Java String object. I need to extract only digits from it. I'll give an example:

"123-456-789" I want "123456789"

Is there a library function that extracts only digits?

Thanks for the answers. Before I try these I need to know if I have to install any additional llibraries?


Solution 1:

You can use regex and delete non-digits.

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

Solution 2:

Here's a more verbose solution. Less elegant, but probably faster:

public static String stripNonDigits(
            final CharSequence input /* inspired by seh's comment */){
    final StringBuilder sb = new StringBuilder(
            input.length() /* also inspired by seh's comment */);
    for(int i = 0; i < input.length(); i++){
        final char c = input.charAt(i);
        if(c > 47 && c < 58){
            sb.append(c);
        }
    }
    return sb.toString();
}

Test Code:

public static void main(final String[] args){
    final String input = "0-123-abc-456-xyz-789";
    final String result = stripNonDigits(input);
    System.out.println(result);
}

Output:

0123456789

BTW: I did not use Character.isDigit(ch) because it accepts many other chars except 0 - 9.

Solution 3:

public String extractDigits(String src) {
    StringBuilder builder = new StringBuilder();
    for (int i = 0; i < src.length(); i++) {
        char c = src.charAt(i);
        if (Character.isDigit(c)) {
            builder.append(c);
        }
    }
    return builder.toString();
}

Solution 4:

Using Google Guava:

CharMatcher.inRange('0','9').retainFrom("123-456-789")

UPDATE:

Using Precomputed CharMatcher can further improve performance

CharMatcher ASCII_DIGITS=CharMatcher.inRange('0','9').precomputed();  
ASCII_DIGITS.retainFrom("123-456-789");