如何在正则表达式中使用非捕获组,即(?:),它们有什么好处?


当前回答

打开您的Google Chrome devTools,然后单击Console选项卡:并键入以下内容:

"Peace".match(/(\w)(\w)(\w)/)

运行它,您将看到:

["Pea", "P", "e", "a", index: 0, input: "Peace", groups: undefined]

JavaScript RegExp引擎捕获三个组,索引为1、2、3的项。现在使用非捕获标记来查看结果。

"Peace".match(/(?:\w)(\w)(\w)/)

结果是:

["Pea", "e", "a", index: 0, input: "Peace", groups: undefined]

这是显而易见的非捕获组。

其他回答

在复杂的正则表达式中,可能会出现这样的情况:您希望使用大量的组,其中一些组用于重复匹配,另一些组用于提供反向引用。默认情况下,匹配每个组的文本将加载到backreference数组中。如果我们有很多组,并且只需要能够从backreference数组中引用其中的一些组,我们可以重写此默认行为,告诉正则表达式某些组只用于重复处理,不需要捕获并存储在backreference阵列中。

?: 当您想对表达式进行分组,但不想将其保存为字符串的匹配/捕获部分时,使用。

一个例子是匹配IP地址:

/(?:\d{1,3}\.){3}\d{1,3}/

请注意,我不在乎保存前3个八位字节,但(?:…)分组允许我缩短正则表达式,而不会导致捕获和存储匹配项的开销。

我想我会给你答案。在未检查匹配是否成功的情况下,不要使用捕获变量。

除非匹配成功,否则捕获变量$1等无效,并且它们也不会被清除。

#!/usr/bin/perl  
use warnings;
use strict;   
$_ = "bronto saurus burger";
if (/(?:bronto)? saurus (steak|burger)/)
{
    print "Fred wants a  $1";
}
else
{
    print "Fred dont wants a $1 $2";
}

在上面的示例中,为了避免在$1中捕获bronto,使用了(?:)。

如果模式匹配,则$1被捕获为下一个分组模式。

因此,输出如下:

Fred wants a burger

如果不希望保存匹配项,则此选项很有用。

我是一名JavaScript开发人员,将尝试解释其与JavaScript相关的意义。

考虑一个场景,你想将猫与动物相匹配当你想要匹配猫和动物时,两者之间应该有一个平衡点。

 // this will ignore "is" as that's is what we want
"cat is animal".match(/(cat)(?: is )(animal)/) ;
result ["cat is animal", "cat", "animal"]

 // using lookahead pattern it will match only "cat" we can
 // use lookahead but the problem is we can not give anything
 // at the back of lookahead pattern
"cat is animal".match(/cat(?= is animal)/) ;
result ["cat"]

 //so I gave another grouping parenthesis for animal
 // in lookahead pattern to match animal as well
"cat is animal".match(/(cat)(?= is (animal))/) ;
result ["cat", "cat", "animal"]

 // we got extra cat in above example so removing another grouping
"cat is animal".match(/cat(?= is (animal))/) ;
result ["cat", "animal"]

(?:…)充当一个组(…),但不捕获匹配的数据。它确实比标准的捕获组效率高得多。当你想对某个东西进行分组,但以后不需要重用它时,就可以使用它了@托托