我有一个长字符串。如何用正则表达式将其中的数字拆分为数组?
我有一个长字符串。如何用正则表达式将其中的数字拆分为数组?
myStr = myStr.replaceAll( "[^\\d]", "" )
myStr = myStr.replaceAll("[\\D]", "");
- Jonas Fagundess/\\D+//
替换字符串中的非数字字符,更易读。 - Adil从字符串中删除所有非数字字符的另一种方法:
String newString = oldString.replaceAll("[^0-9]", "");
String str= "somestring";
String[] values = str.split("\\D+");
另一个正则表达式的解决方案:
string.replace(/\D/g,''); //remove the non-Numeric
同样地,您可以
string.replace(/\W/g,''); //remove the non-alphaNumeric
在正则表达式中,“\”符号会将其后面的字母作为模板: \w -- 表示包含字母和数字,\W -- 表示不包含字母和数字。当你将字母大写时,意义将被取反。
StringBuilder sb = new StringBuilder();
test.chars().mapToObj(i -> (char) i).filter(Character::isDigit).forEach(sb::append);
System.out.println(sb.toString());
这在Flex SDK 4.14.0中有效。
myString.replace(/[^0-9&&^.]/g, "");
可以将字符串中除数字、&和.之外的字符替换为空。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);
}
}
之前的答案会去掉你的小数点。如果你想保留小数,你可能需要
String str = "My values are : 900.00, 700.00, 650.50";
String[] values = str.split("[^\\d.?\\d]");
// split on wherever they are not digits except the '.' decimal point
// values: { "900.00", "700.00", "650.50"}
\\d
?[^\\d.?\\d]
是一个否定的字符类,匹配任何不是数字、点或问号的字符。 - Toto[^\\d.]
就足够了,而且实现的效果也一样。 - Toto不使用正则表达式的简单方法:
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();
}