Are non-capturing groups redundant?

大城市里の小女人 提交于 2019-12-17 04:37:09

问题


Are optional non-capturing groups redundant?

Is the following regex:

(?:wo)?men

semantically equivalent to the following regex?

(wo)?men

回答1:


Your (?:wo)?men and (wo)?men are semantically equivalent, but technically are different, namely, the first is using a non-capturing and the other a capturing group. Thus, the question is why use non-capturing groups when we have capturing ones?

Non-caprturing groups are of help sometimes.

  1. To avoid excessive number of backreferences (remember that it is sometimes difficult to use backreferences higher than 9)
  2. To avoid the problem with 99 numbered backreferences limit (by reducing the number of numbered capturing groups) (source: Regular-expressions.info: Most regex flavors support up to 99 capturing groups and double-digit backreferences.)
    NOTE this does not pertain to Java regex engine, nor to PHP or .NET regex engines.
  3. To lessen the overhead caused by storing the captures in the stack
  4. We can add more groupings to existing regex without ruining the order of capturing groups.

Also, it is just makes our matches cleaner:

You can use a non-capturing group to retain the organisational or grouping benefits but without the overhead of capturing.

It does not seem a good idea to re-factor existing regular expressions to convert capturing to non-capturing groups, since it may ruin the code or require too much effort.



来源:https://stackoverflow.com/questions/31500422/are-non-capturing-groups-redundant

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!