Javascript正则表达式中被动(非捕获)组的目的是什么? [英] What is the purpose of the passive (non-capturing) group in a Javascript regex?
问题描述
Javascript正则表达式中被动组的目的是什么?
What is the purpose of the passive group in a Javascript regex?
被动组的前面是一个问号冒号:(? :group)
The passive group is prefaced by a question mark colon: (?:group)
换句话说,这两件事情看起来是一样的:
In other words, these 2 things appear identical:
"hello world".match(/hello (?:world)/)
"hello world".match(/hello world/)
在什么情况下你需要非捕获组以及为什么?
In what situations do you need the non capturing group and why?
推荐答案
非捕获与普通(捕获)组只有一个区别:它们不需要正则表达式引擎记住它们匹配的内容。
Non-capturing have just one difference from "normal" (capturing) groups: they don't require the regex engine to remember what they matched.
用例是有时你必须(或应该)使用一个组,不是因为你对它所捕获的内容感兴趣而是出于语法原因。在这些情况下,使用非捕获组而不是标准捕获组是有意义的,因为它不太占用资源 - 但如果您不关心它,捕获组将以完全相同的方式运行。
The use case is that sometimes you must (or should) use a group not because you are interested in what it captures but for syntactic reasons. In these situations it makes sense to use a non-capturing group instead of a "standard" capturing one because it is less resource intensive -- but if you don't care about that, a capturing group will behave in the exact same manner.
您的具体示例并不能很好地使用非捕获组,因为这两个表达式完全相同。一个更好的例子可能是:
Your specific example does not make a good case for using non-capturing groups exactly because the two expressions are identical. A better example might be:
input.match(/hello (?:world|there)/)
这篇关于Javascript正则表达式中被动(非捕获)组的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!