我需要提取java.lang.String
中找到的第一个整数,并且不确定是否尝试使用substring
方法或正则表达式方法:
// Want to extract the 510 into an int.
String extract = "PowerFactor510";
// Either:
int num = Integer.valueof(extract.substring(???));
// Or a regex solution, something like:
String regex = "\\d+";
Matcher matcher = new Matcher(regex);
int num = matcher.find(extract);
所以我问:
注意:字符串始终以单词PowerFactor
开头,后跟非负整数。提前谢谢!
答案 0 :(得分:9)
字符串将始终以单词“PowerFactor”开头,后跟a 非负整数
这意味着你确切知道你会在哪个索引找到这个数字,我想你最好直接使用子字符串,至少考虑一下它的性能会比搜索和匹配工作快得多。
extract.substring("PowerFactor".length());
我找不到任何直接的比较,但你可以阅读以下两个选项中的每一个:
答案 1 :(得分:1)
有点好奇并尝试了下面的
String extract = "PowerFactor510";
long l = System.currentTimeMillis();
System.out.println(extract.replaceAll("\\D", ""));
System.out.println(System.currentTimeMillis() - l);
System.out.println();
l = System.currentTimeMillis();
System.out.println(extract.substring("PowerFactor".length()));
System.out.println(System.currentTimeMillis() - l);
并且它调整了第二次测试更快,所以substring
获胜。