如何在正则表达式中使用非捕获组,即(?:),它们有什么好处?
当前回答
历史动机:
非捕获组的存在可以用括号来解释。
考虑表达式(a|b)c和a|bc,由于串联优先于|,这些表达式分别表示两种不同的语言({ac,bc}和{a,bc})。
然而,括号也用作匹配组(如其他答案所解释的…)。
当您想有括号但不想捕获子表达式时,可以使用NON-CAPTURING GROUPS。在示例中,(?:a|b)c
其他回答
打开您的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]
这是显而易见的非捕获组。
简单的答案
使用它们来确保在这里出现几种可能性中的一种(?:一个|两个)或可选短语camp(?:站点)?或者一般来说,任何你想建立一个组/短语/部分而不需要特别提及的地方。
他们将您捕获的组数保持在最小值。
我是一名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"]
它使组不捕获,这意味着该组匹配的子字符串将不包含在捕获列表中。ruby中的一个示例说明了区别:
"abc".match(/(.)(.)./).captures #=> ["a","b"]
"abc".match(/(?:.)(.)./).captures #=> ["b"]
历史动机:
非捕获组的存在可以用括号来解释。
考虑表达式(a|b)c和a|bc,由于串联优先于|,这些表达式分别表示两种不同的语言({ac,bc}和{a,bc})。
然而,括号也用作匹配组(如其他答案所解释的…)。
当您想有括号但不想捕获子表达式时,可以使用NON-CAPTURING GROUPS。在示例中,(?:a|b)c