非捕获组是多余的吗? [英] Are non-capturing groups redundant?
问题描述
可选的非捕获组是多余的吗?
Are optional non-capturing groups redundant?
以下是正则表达式:
(?:wo)?men
在语义上等同于以下正则表达式?
semantically equivalent to the following regex?
(wo)?men
推荐答案
你的(?:wo)?男人
和(wo)?men
在语义上是等价的,但在技术上是不同的,即第一个是使用非捕获而另一个是捕获组。因此,问题是为什么在捕获时使用非捕获组?
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.
- 避免过多的反向引用(请记住,有时很难使用高于9的反向引用)
- 避免99编号反向引用限制的问题(通过减少编号的捕获组的数量)(来源: Regular-expressions.info :大多数正则表达式支持多达99个捕获组和两位数的反向引用。)
注意这不适用于Java正则表达式引擎,也不适用于PHP或.NET正则表达式引擎。 - 要减少因将堆栈存储在堆栈中而导致的开销
- 我们可以在不破坏捕获组的顺序的情况下为现有正则表达式添加更多分组。
- To avoid excessive number of backreferences (remember that it is sometimes difficult to use backreferences higher than 9)
- 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. - To lessen the overhead caused by storing the captures in the stack
- We can add more groupings to existing regex without ruining the order of capturing groups.
此外,它只是让我们的比赛更清晰:
您可以使用非捕获组来保留组织或分组权益,但不会产生捕获的开销。
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.
这篇关于非捕获组是多余的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!