Want to improve this question? Add details and clarify the problem by editing this post.开发者_运维问答
Closed 2 years ago.
Improve this questionI have a long string. What is the regular expression to split the numbers into the array?
Are you removing or splitting? This will remove all the non-numeric characters.
myStr = myStr.replaceAll( "[^\\d]", "" )
One more approach for removing all non-numeric characters from a string:
String newString = oldString.replaceAll("[^0-9]", "");
String str= "somestring";
String[] values = str.split("\\D+");
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 capitalize the letter.
You will want to use the String class' Split() method and pass in a regular expression of "\D+" which will match at least one non-number.
myString.split("\\D+");
Java 8 collection streams :
StringBuilder sb = new StringBuilder();
test.chars().mapToObj(i -> (char) i).filter(Character::isDigit).forEach(sb::append);
System.out.println(sb.toString());
This works in Flex SDK 4.14.0
myString.replace(/[^0-9&&^.]/g, "");
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);
}
}
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 except the '.' decimal point
// values: { "900.00", "700.00", "650.50"}
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();
}
精彩评论