Java 已知起始索引时子字符串与正则表达式的性能比较
我需要提取在Java 已知起始索引时子字符串与正则表达式的性能比较,java,regex,string,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 re
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);
所以我问:
- 这里哪种解决方案更合适,为什么?;及
- 如果子字符串方法更合适,我可以用什么来表示数字的开头
- 否则,如果regex是合适的解决方案,那么我应该使用什么regex/pattern/matcher/方法来提取数字
PowerFactor
开头,后跟一个非负整数。提前谢谢
字符串总是以单词“PowerFactor”开头,后跟一个
非负整数
这意味着您确切地知道将在哪个索引处找到数字,我认为您最好直接使用子字符串,至少考虑到性能,它将比搜索和匹配工作快得多
extract.substring("PowerFactor".length());
我找不到任何直接的比较,但您可以阅读两个选项中的每一个:
- 有点好奇,尝试了以下方法
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);
第二个测试的速度要快得多,因此
子字符串
获胜。由于处理速度更快,正则表达式更可取。正则表达式真的比子字符串(11)
快吗?第一部分总是固定的。。。我不认为解析一个正则表达式、遍历字符串并提取适当的组会比仅仅切掉前11个字符更快……你到底为什么要把\D
放在括号里?@tchrist编辑了答案这是一个可怕的测试。String类的replaceAll方法在处理正则表达式之前对其执行内联编译。该方法不能针对模式/匹配器或任何与正则表达式相关的对象生成合适的测试。您看到的速度差异与JVM中的对象创建和GC有关。