简体   繁体   English

用字符串中的空字符替换所有非数字

[英]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? 有什么建议?

Java不是Perl :)试试"[^0-9]+"

Try this: 试试这个:

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

Use following where enumValue is the input string. 如果enumValue是输入字符串,请使用以下enumValue

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. 例如:输入为_126576,输出为126576。

Hope this helps. 希望这可以帮助。

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

This does what you want. 这样做你想要的。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM