Question

Please give an example where the difference between greedy and lazy versions of "repeat-exactly-m-times" quantifier can be seen.
The question arose from here and here.
If there are no differences then what for the {m}? quantifier exists?

Était-ce utile?

La solution 2

As said in comments, Oniguruma regexp engine treats it differently, as an exception: {m}? is not a non-greedy exact m (which is same as greedy exact m), but 0-or-m. All the other engines I tried did as other posters say: it makes no difference.

The reason for the non-greedy exact m to exist: if it didn't, it's an exception. Exceptions are harder to remember, and harder to implement - it's extra work, and in this case, as the semantics is equal, it doesn't hurt anyone.

I love Oniguruma, and appreciate they might have wanted to change the unneeded bit into something more usable and efficient, but this looks like a bug waiting to happen. Fortunately, no-one sane writes non-greedy exact m...

Autres conseils

I don't believe there is any real difference between {m} and {m}? since each specifies exactly m times. However, there is a difference between {m,} and {m,}? (and {m,}+, while we're at it). It's appropriate and needed for quantifiers in general, even if it isn't needed for that particular case.

Doesn't make a difference in exact match {m}.

However, will make a difference with {m,} as greedy qualifiers match as many characters as possible, whereas lazy qualifiers match as few as possible.


Given the string "Baaaaaaaaaaaa"

The regex (B[a]{2,}?) would match "Baa"

The regex (B[a]{2,}) would match "Baaaaaaaaaaaa"


Whereas, with the exact match {m}:

The regex (B[a]{2}?) would match "Baa"

The regex (B[a]{2}) would also match "Baa"

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top