将包含数字的字符串解析(转换)为数字类型
Parse(convert) String containing number to Number type
java 中从文本中提取数字并进行解析的最佳做法是什么?
例如:
String s = "Availability in 20 days";
请不要拘泥于示例,我正在寻找良好的通用实践和场景。
谢谢。
使用正则表达式:
Pattern p = Pattern.compile("-?\d+");
Matcher m = p.matcher("Availability in 20 days");
while (m.find()) {
int number = Integer.parseInt(m.group());
...
}
regex + replaceAll 怎么样?
代码:
String after = str.replaceAll("\D+", "");
我不确定最佳实践,但我会在这个堆栈溢出问题中描述一种方法。
How to extract numbers from a string and get an array of ints?
我不太确定你想做什么,但这里有一些可能对你有帮助的解决方案:
列表项使用 .indexOf 和 .substring 在字符串中查找数字
示例:
String s;
String str = new String("1 sentence containing 5 words and 3 numbers.");
ArrayList<Integer> integers = new ArrayList<Integer>();
for (int i = 0; i <= 9; i++) {
int start = 0;
while (start != -1) {
String sub = str.substring(start);
int x = sub.indexOf(i);
if (x != -1) {
s = sub.substring(x, x+1);
integers.add(Integer.parseInt(s));
start = x;
} else {
//number not found
start = -1;
}
}
}
一次提取一个字符,尝试解析,如果没有异常,就是一个数字。我绝对不推荐此解决方案,但它也应该有效。不幸的是,我不能告诉你哪种方法更快,但我可以想象 - 尽管命令较少 - 考虑到抛出的几个异常,第二个版本更慢。
String s;
int integ;
ArrayList<Integer> integers = new ArrayList<Integer>();
String str = new String("1 sentence containing 5 words and 3 numbers.");
for (int i = 0; i < str.length(); i++) {
s = str.substring(i,i+1);
try {
integ = Integer.parseInt(s);
integers.add(integ);
} catch (NumberFormatException nfe) {
//nothing
}
}
如果有多个号码则
String[] after = str.replaceAll("\D+", " ").split("\s+");
java 中从文本中提取数字并进行解析的最佳做法是什么?
例如:
String s = "Availability in 20 days";
请不要拘泥于示例,我正在寻找良好的通用实践和场景。
谢谢。
使用正则表达式:
Pattern p = Pattern.compile("-?\d+");
Matcher m = p.matcher("Availability in 20 days");
while (m.find()) {
int number = Integer.parseInt(m.group());
...
}
regex + replaceAll 怎么样?
代码:
String after = str.replaceAll("\D+", "");
我不确定最佳实践,但我会在这个堆栈溢出问题中描述一种方法。
How to extract numbers from a string and get an array of ints?
我不太确定你想做什么,但这里有一些可能对你有帮助的解决方案:
列表项使用 .indexOf 和 .substring 在字符串中查找数字
示例:
String s; String str = new String("1 sentence containing 5 words and 3 numbers."); ArrayList<Integer> integers = new ArrayList<Integer>(); for (int i = 0; i <= 9; i++) { int start = 0; while (start != -1) { String sub = str.substring(start); int x = sub.indexOf(i); if (x != -1) { s = sub.substring(x, x+1); integers.add(Integer.parseInt(s)); start = x; } else { //number not found start = -1; } } }
一次提取一个字符,尝试解析,如果没有异常,就是一个数字。我绝对不推荐此解决方案,但它也应该有效。不幸的是,我不能告诉你哪种方法更快,但我可以想象 - 尽管命令较少 - 考虑到抛出的几个异常,第二个版本更慢。
String s; int integ; ArrayList<Integer> integers = new ArrayList<Integer>(); String str = new String("1 sentence containing 5 words and 3 numbers."); for (int i = 0; i < str.length(); i++) { s = str.substring(i,i+1); try { integ = Integer.parseInt(s); integers.add(integ); } catch (NumberFormatException nfe) { //nothing } }
如果有多个号码则
String[] after = str.replaceAll("\D+", " ").split("\s+");