'Replace all non digits with an empty character in a string

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?



Solution 1:[1]

Try this:

public static String removeNonDigits(final String str) {
   if (str == null || str.length() == 0) {
       return "";
   }
   return str.replaceAll("\\D+", "");
}

Solution 2:[2]

Use following where enumValue is the input string.

enumValue.replaceAll("[^0-9]","")

This will take the string and replace all non-number digits with a "".

eg: input is _126576, the output will be 126576.

Hope this helps.

Solution 3:[3]

public String replaceNonDigits(final String string) {
    if (string == null || string.length() == 0) {
        return "";
    }
    return string.replaceAll("[^0-9]+", "");
}

This does what you want.

Solution 4:[4]

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

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 mtk
Solution 3
Solution 4 budi