Replace all non digits with an empty character in

2020-08-09 07:34发布

问题:

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?

回答1:

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



回答2:

Try this:

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


回答3:

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.



回答4:

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

This does what you want.



回答5:

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