如何从java中的字符串中删除非数字字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1533659/
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
How do I remove the non-numeric character from a string in java?
提问by unj2
I have a long string. What is the regular expression to split the numbers into the array?
我有一个很长的字符串。将数字拆分为数组的正则表达式是什么?
回答by Stefan Kendall
Are you removing or splitting? This will remove all the non-numeric characters.
你是删除还是拆分?这将删除所有非数字字符。
myStr = myStr.replaceAll( "[^\d]", "" )
回答by Stephen Mesa
回答by eveliotc
String str= "somestring";
String[] values = str.split("\D+");
回答by Andrey
One more approach for removing all non-numeric characters from a string:
从字符串中删除所有非数字字符的另一种方法:
String newString = oldString.replaceAll("[^0-9]", "");
回答by Matthias Gerth
This works in Flex SDK 4.14.0
这适用于 Flex SDK 4.14.0
myString.replace(/[^0-9&&^.]/g, "");
myString.replace(/[^0-9&&^.]/g, "");
回答by Suleiman Alrosan
you could use a recursive method like below:
您可以使用如下递归方法:
public static String getAllNumbersFromString(String input) {
if (input == null || input.length() == 0) {
return "";
}
char c = input.charAt(input.length() - 1);
String newinput = input.substring(0, input.length() - 1);
if (c >= '0' && c<= '9') {
return getAllNumbersFromString(newinput) + c;
} else {
return getAllNumbersFromString(newinput);
}
}
回答by shridutt kothari
Simple way without using Regex:
不使用正则表达式的简单方法:
public static String getOnlyNumerics(String str) {
if (str == null) {
return null;
}
StringBuffer strBuff = new StringBuffer();
char c;
for (int i = 0; i < str.length() ; i++) {
c = str.charAt(i);
if (Character.isDigit(c)) {
strBuff.append(c);
}
}
return strBuff.toString();
}
回答by krizajb
Another regex solution:
另一个正则表达式解决方案:
string.replace(/\D/g,''); //remove the non-Numeric
Similarly, you can
同样,你可以
string.replace(/\W/g,''); //remove the non-alphaNumeric
In RegEX, the symbol '\' would make the letter following it a template: \w-- alphanumeric, and \W- Non-AlphaNumeric, negates when you capitalizethe letter.
在 RegEX 中,符号 '\' 会使后面的字母成为模板:\w-- alphanumeric和\W- Non-AlphaNumeric,当您将字母大写时否定。
回答by Matthias Gerth
StringBuilder sb = new StringBuilder();
test.chars().mapToObj(i -> (char) i).filter(Character::isDigit).forEach(sb::append);
System.out.println(sb.toString());
回答by Jenna Leaf
Previous answers will strip your decimal point. If you want to save your decimal, you might want to
以前的答案将删除您的小数点。如果你想保存你的十进制,你可能想要
String str = "My values are : 900.00, 700.00, 650.50";
String[] values = str.split("[^\d.?\d]");
// split on wherever they are not digits ( but don't split digits embedded with decimal point )