假设一个目标字符串一方面是任意的,但另一方面,保证包含一个单个十进制数(1或更多位数),我想出了以下正则正则表达式:
.*?(\d+).*?因此,如果目标字符串是“(这是数字200)",例如,Matcher.group(1)将包含该数字。
是否有更优的正则表达式模式(或非正则表达式方法)来提取这个数字?
所谓“最优”,我指的是最快的(可能有最少的CPU周期)。只有爪哇。
发布于 2011-09-09 15:24:31
我相信regex和parseInt会为您提供足够好的性能。不过,为了你的兴趣,我把它比作一个简单的循环。
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;
}版画
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发布于 2011-09-09 14:40:17
光(\d+)就够了。
https://stackoverflow.com/questions/7363322
复制相似问题