Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

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 negative look behind", so that Foo is not allowed before bar, but this is not working.

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/

it behaves like I expect. It matches only the bar and not the bar in Foobar.

But that's exactly the same behaviour as if I used only /bar/ or /^bar/.

Is the quantifier {0} only a useless side effect, or is there really a useful behaviour for that?

like image 376
stema Avatar asked Sep 22 '11 08:09

stema


2 Answers

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.

like image 171
Kobi Avatar answered Oct 20 '22 01:10

Kobi


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.

like image 44
Peter G. Avatar answered Oct 20 '22 00:10

Peter G.