views:

963

answers:

4
public static String removeNonDigits(final String str) {
   if (str == null || str.length() == 0) {
       return "";
   }
   return str.replaceAll("/[^0-9]/g", "");
}

This should only get the Digits and return but not doing it as expected! Any suggestions?

+4  A: 

Java is not Perl :) Try "[^0-9]+"

Aaron Digulla
LOL.. Thank you.. :)
+4  A: 

Try this:

public static String removeNonDigits(final String str) {
   if (str == null || str.length() == 0) {
       return "";
   }
   return str.replaceAll("\\D+", "");
}
Yannick M.
You need to escape the slash (for Java's sake, not the regex): "\\D+"
Jon Skeet
Woops, \\fixed\\
Yannick M.
Thanks guys.. :)
A: 
public String replaceNonDigits(final String string) {
    if (string == null || string.length() == 0) {
        return "";
    }
    return string.replaceAll("[^0-9]+", "");
}

This does what you want.

Per Östlund
+1  A: 

I'd recommend for this particular case just having a small loop over the string

(untested)

StringBuilder sb = new StringBuilder;
for(int i = 0; i < s.length(); i++) {
   char ch = s.charAt(i);
   if (ch =='0' || ch == '1' || ch == '2'....) {
     sb.add(ch);
   }
}
return sb.toString();
Thorbjørn Ravn Andersen
Character.isDigit(...) is a better option than '(ch =='0' || ch == '1' || ch == '2'....)' IMO.
Bart Kiers