Java 用字符串中的空字符替换所有非数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1486295/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replace all non digits with an empty character in a string
提问by
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?
这应该只获取数字并返回,但不会按预期进行!有什么建议?
采纳答案by Aaron Digulla
Java is not Perl :) Try "[^0-9]+"
Java 不是 Perl :) 试试 "[^0-9]+"
回答by Yannick Motton
Try this:
尝试这个:
public static String removeNonDigits(final String str) {
if (str == null || str.length() == 0) {
return "";
}
return str.replaceAll("\D+", "");
}
回答by Per ?stlund
public String replaceNonDigits(final String string) {
if (string == null || string.length() == 0) {
return "";
}
return string.replaceAll("[^0-9]+", "");
}
This does what you want.
这做你想要的。
回答by Thorbj?rn Ravn Andersen
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();
回答by raj
Use following where enumValue
is the input string.
使用以下 whereenumValue
是输入字符串。
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.
希望这可以帮助。