[java] Extract digits from a string in Java

I inspired by code Sean Patrick Floyd and little rewrite it for maximum performance i get.

public static String stripNonDigitsV2( CharSequence input ) {
    if (input == null)
        return null;
    if ( input.length() == 0 )
        return "";

    char[] result = new char[input.length()];
    int cursor = 0;
    CharBuffer buffer = CharBuffer.wrap( input );

    while ( buffer.hasRemaining() ) {
        char chr = buffer.get();
        if ( chr > 47 && chr < 58 )
            result[cursor++] = chr;
    }

    return new String( result, 0, cursor );
}

i do Performance test to very long String with minimal numbers and result is:

  • Original code is 25,5% slower
  • Guava approach is 2.5-3 times slower
  • Regular expression with D+ is 3-3.5 times slower
  • Regular expression with only D is 25+ times slower

Btw it depends on how long that string is. With string that contains only 6 number is guava 50% slower and regexp 1 times slower