What is the purpose of the passive (non-capturing) group in a Javascript regex?

后端 未结 5 1799
渐次进展
渐次进展 2021-01-12 11:05

What is the purpose of the passive group in a Javascript regex?

The passive group is prefaced by a question mark colon: (?:group)

In other words

5条回答
  •  被撕碎了的回忆
    2021-01-12 12:04

    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)/)
    

提交回复
热议问题