2

Both expressions work for me:

E1=> work(?:\s+)?group 

E2=> work(\s+)?group

I need to capture workgroup OR work group considering the space could be a line break (\s+)?

However, the first expression has a non-capture groups (?: and I am wondering if it is worse or better in the performance/fast output of the Regex. In other words, in terms of performance, what is the best expression?

4

1 回答 1

1

答案实际上取决于您使用的正则表达式引擎的内部结构。

在 Javascript 中,我不知道哪个更快。

在 PHP 中,捕获组可能会更快一些。这是一个简单的测试,带有您的正则表达式的简化版本。

<?php
$string = "WORD1".str_repeat(" someword",100000);
$regex1="~WORD1(?:\s+\w+){0,2}~";
$regex2="~WORD1(\s+\w+){0,2}~";

$start=microtime(TRUE);
for ($i=1;$i<1000000;$i++) preg_match($regex1,$string);
$noncapend=microtime(TRUE);
for ($i=1;$i<1000000;$i++) preg_match($regex2,$string);
$withcapend=microtime(TRUE);
$noncap = $noncapend-$start;
$withcap = $withcapend-$noncapend;
$diff = 100*($withcap-$noncap)/$noncap;
echo "Non-Capture Group: ".$noncap."<br />";
echo "Capture Group: ".$withcap."<br />";
echo "difference: ".$diff." percent longer<br />";

?>

输出:

请注意,您每次都会得到不同的结果。

Non-Capture Group: 1.092001914978
Capture Group: 1.0608019828796
difference: -2.857131628658 percent longer
于 2014-04-26T22:44:28.053 回答