Replace all non digits with an empty character in

2020-08-09 07:50发布

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?

5条回答
我想做一个坏孩纸
2楼-- · 2020-08-09 07:57

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

查看更多
祖国的老花朵
3楼-- · 2020-08-09 07:57
public String replaceNonDigits(final String string) {
    if (string == null || string.length() == 0) {
        return "";
    }
    return string.replaceAll("[^0-9]+", "");
}

This does what you want.

查看更多
Fickle 薄情
4楼-- · 2020-08-09 08:06

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();
查看更多
我想做一个坏孩纸
5楼-- · 2020-08-09 08:10

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.

查看更多
神经病院院长
6楼-- · 2020-08-09 08:16

Try this:

public static String removeNonDigits(final String str) {
   if (str == null || str.length() == 0) {
       return "";
   }
   return str.replaceAll("\\D+", "");
}
查看更多
登录 后发表回答