首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >提取任意字符串中单个十进制数的最佳正则表达式

问提取任意字符串中单个十进制数的最佳正则表达式
EN

Stack Overflow用户
提问于 2011-09-09 14:38:01
回答 2查看 760关注 0票数 0

假设一个目标字符串一方面是任意的,但另一方面,保证包含一个单个十进制数(1或更多位数),我想出了以下正则正则表达式:

代码语言:javascript
复制
.*?(\d+).*?

因此,如果目标字符串是“(这是数字200)",例如,Matcher.group(1)将包含该数字。

是否有更优的正则表达式模式(或非正则表达式方法)来提取这个数字?

所谓“最优”,我指的是最快的(可能有最少的CPU周期)。只有爪哇。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-09-09 15:24:31

我相信regex和parseInt会为您提供足够好的性能。不过,为了你的兴趣,我把它比作一个简单的循环。

代码语言:javascript
复制
public static final Pattern DIGITS = Pattern.compile("(\\d+)");

public static void main(String[] args) {
  String text = "Some text before a number 123456 and some after";
  for (int i = 0; i < 5; i++) {
    timeRegex(text);
    timeLooping(text);
  }
}

private static int timeLooping(String text) {
  int ret = 0;
  final int runs = 1000;
  long start = System.nanoTime();
  for (int r = 0; r < runs; r++) {
    for (int i = 0; i < text.length(); i++) {
      char ch = text.charAt(i);
      if (ch <= '9' && ch >= '0')
        ret = ret * 10 + ch - '0';
      else if (ret > 0)
        break;
    }
  }
  long time = System.nanoTime() - start;
  System.out.printf("Took %,d ns to use a loop on average%n", time / runs);
  return ret;
}

private static int timeRegex(String text) {
  int ret = 0;
  final int runs = 1000;
  long start = System.nanoTime();
  for (int r = 0; r < runs; r++) {
    Matcher m = DIGITS.matcher(text);
    if (m.find())
      ret = Integer.parseInt(m.group());
  }
  long time = System.nanoTime() - start;
  System.out.printf("Took %,d ns to use a matcher on average%n", time / runs);
  return ret;
}

版画

代码语言:javascript
复制
Took 19,803 ns to use a matcher on average
Took 85 ns to use a loop on average
Took 12,411 ns to use a matcher on average
Took 83 ns to use a loop on average
Took 8,199 ns to use a matcher on average
Took 79 ns to use a loop on average
Took 11,156 ns to use a matcher on average
Took 104 ns to use a loop on average
Took 4,527 ns to use a matcher on average
Took 94 ns to use a loop on average
票数 2
EN

Stack Overflow用户

发布于 2011-09-09 14:40:17

光(\d+)就够了。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7363322

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档