Skip to content

Quantifiers and greed

How many

*, +, ? and {n,m} — and what each one does to the empty string.

A quantifier repeats the thing immediately before it. a* is zero or more a, a+ is one or more, a? is zero or one, and a{2,4} is between two and four.

{n} is exactly n, and {n,} is n or more. There is no upper-bound-only form; {,4} is not a quantifier and is matched as four literal characters.

* and ? can match nothing, and a pattern made only of those matches the empty string everywhere. a* succeeds at every position in every input, which is why searching globally with it produces a run of empty matches.

That is not a bug in the engine. It is what the pattern says, and it is the reason a * where you meant + produces results that look almost right.

A quantifier binds to one thing: the character, class or group directly before it. ab+ is an a followed by one or more b. To repeat both, put them in a group: (?:ab)+.

Matcher

Every claim on the left has a pattern under it. Press one and it runs here, against the same engine that grades a task.