Course of Raku / Regexes and grammars / Regexes / Quantifiers

Greedy and frugal matching

By default, a quantifier is greedy: it matches as much as it possibly can while still letting the rest of the pattern succeed. Consider matching from the first < to a >:

say '<a><b>' ~~ / '<' .+ '>' /; # 「<a><b>」

The .+ swallowed as much as it could, all the way to the last >, so the match runs across both pairs of brackets.

To make a quantifier frugal (also called lazy or non-greedy), add a ? after it. A frugal quantifier matches as little as possible:

say '<a><b>' ~~ / '<' .+? '>' /; # 「<a>」

Now .+? stops at the first >, so only the first bracketed piece matches.

The ? suffix works on any quantifier: *? and **? are frugal too. Greedy and frugal versions match the same kinds of text — they differ only in how much they take when there is a choice.

Practice

Complete the quiz that covers the contents of this topic.

Course navigation

The times quantifier   |   Quiz — Quantifiers


💪 Or jump directly to the exercises in this section.