Does the quantifier {0} make sense in some scenarios?

前端 未结 4 1566
无人共我
无人共我 2020-12-30 08:14

Example:

/(?:Foo){0}bar/

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

相关标签:
4条回答
  • 2020-12-30 08:29

    An explicit repetition count of zero can be useful in automatically generated regular expressions. You avoid coding a special case for zero repetitions this way.

    0 讨论(0)
  • 2020-12-30 08:42

    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:

    • The best one - use of the group in recursive regular expressions (or other weird constructs). Perl, for example, has (?(DEFINE) ) for the same use.
      A quick example - in PHP, this will match barFoo (working example):

      preg_match("/(?:(Foo)){0}bar(?1)/", "barFoo", $matches);
      
    • Adding a failed captured group (named or numbered) to the result matches.

    • Keeping the indices of all groups intact in case the pattern was refactored.

    Less good uses, as Peter suggested are useful in:

    • 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 讨论(0)
  • 2020-12-30 08:46

    I can't think of a single good reason to use x{0}. But I can think of several why it should be avoided:

    • It's useless since it always matches.
    • It slows the regex engine down (unless the regex is precompiled).
    • It's probably a sign of misunderstanding by the regex author.

    I'm willing to bet that someone who writes (?:foo){0} is trying to say "make sure that foo doesn't match here", which of course fails because the empty string can always be matched, whether foo is there or not. That's what negative lookaround assertions are for. (?<!foo)bar etc.

    0 讨论(0)
  • 2020-12-30 08:51

    In traditional regular expressions, /x{0}/ (language = { xn : x = 0}) would mean "match exactly 0 of x", which is the same thing as // (language = { Λ }). Since the two are equivalent, you should be able to remove any /x{0}/ you find lying around.

    But PCREs and other extensions to regular expressions can get quite byzantine. I would not be surprised if /x{0}/ did something in Perl. I would be disgusted, but not surprised.

    I think it's probably some artifact of a program that automatically generates regular expressions but doesn't simplify them. Which is a shame, since it's so easy to write programs that simplify regular expressions.

    0 讨论(0)
提交回复
热议问题