启动索引已知时,Substring与RegEx之间的性能比较

时间:2013-03-25 13:24:00

标签: java regex string

我需要提取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开头,后跟非负整数。提前谢谢!

2 个答案:

答案 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获胜。