gpt4 book ai didi

java - 起始索引已知时 Substring 与 RegEx 的性能比较

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:15:52 24 4
gpt4 key购买 nike

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

最佳答案

The string will always begin with the word "PowerFactor" followed by a non-negative integer

这意味着您确切地知道您将在哪个索引处找到数字,我会说您最好直接使用子字符串,至少考虑到性能它会比搜索和匹配工作快得多。

extract.substring("PowerFactor".length());

我找不到任何直接比较,但您可以阅读这两个选项中的每一个:

关于java - 起始索引已知时 Substring 与 RegEx 的性能比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15616066/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com