量词 {0} 在某些情况下有意义吗? [英] Does the quantifier {0} make sense in some scenarios?
问题描述
示例:
/(?:Foo){0}bar/
/(?:Foo){0}bar/
我在另一个答案中看到了类似的内容.起初我想那应该是什么",但后来,好吧,有点消极的看法",所以在 bar
之前不允许 Foo
,但这不起作用.
I saw something like this in another answer. At first I thought "what should that be", but then, "OK could make sense, kind of a negative look behind", so that Foo
is not allowed before bar
, but this is not working.
你可以看到这个 这里在 Regexr:它只匹配 bar
但它还匹配 Foobar
中的 bar
.
当我为行的开头添加一个锚点时:
You can see this here on Regexr: It matches only bar
but it matches also the bar
in Foobar
.
When I add an anchor for the start of the row:
/^(?:Foo){0}bar/
它的行为就像我期望的那样.它只匹配 bar
而不是 Foobar
中的 bar
.
it behaves like I expect. It matches only the bar
and not the bar
in Foobar
.
但这与我只使用 /bar/
或 /^bar/
时的行为完全相同.
But that's exactly the same behaviour as if I used only /bar/
or /^bar/
.
量词 {0}
只是一个无用的副作用,还是真的有一个有用的行为?
Is the quantifier {0}
only a useless side effect, or is there really a useful behaviour for that?
推荐答案
{0}
有好的用途.它允许您定义您目前不打算捕获的组.这在某些情况下很有用:
There are good uses of {0}
. It allows you to define groups that you don't intend to capture at the moment. This can be useful in some cases:
最好的一个 - 在递归正则表达式(或其他奇怪的结构)中使用组.例如,Perl 具有
(?(DEFINE) )
用于相同的用途.
一个快速示例 - 在 PHP 中,这将匹配barFoo
(工作示例):>
preg_match("/(?:(Foo)){0}bar(?1)/", "barFoo", $matches);
将失败的捕获组(命名或编号)添加到结果匹配中.
Adding a failed captured group (named or numbered) to the result matches.
不太好的用途,正如彼得建议的那样:
Less good uses, as Peter suggested are useful in:
- 生成的模式.
- 可读性 - 具有一定重复性的模式,其中
{0}
和{1}
可能会引导人们朝着正确的方向思考.(好吧,不是最好的一点)
- Generated patterns.
- Readability - Patterns with certain duplication, where
{0}
and{1}
may lead thinking in the right direction. (OK, not the best point)
这些都是罕见的情况,在大多数情况下都是错误的.
These are all rare cases, and in most patterns it is a mistake.
这篇关于量词 {0} 在某些情况下有意义吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!