Course of Raku / Regexes and grammars / Regexes / Quantifiers

Star, plus, and question mark

Three symbols cover the most common cases. Each one applies to the item right before it:

  • * — zero or more times
  • + — one or more times
  • ? — zero or one time (optional)

The plus sign matches a run of one or more characters:

say 'aaah' ~~ / a+ /; # 「aaa」

It matched as many as as it could — three of them.

The star is like the plus but also succeeds when there is nothing to match, because zero repetitions are allowed:

say 'colour' ~~ / colou*r /; # 「colour」
say 'color'  ~~ / colou*r /; # 「color」

The question mark makes a piece optional — it matches whether or not the piece is there:

say 'colour' ~~ / colou?r /; # 「colour」
say 'color'  ~~ / colou?r /; # 「color」

Quantifiers apply to whatever comes immediately before them, including a character class. For example, \d+ matches a run of one or more digits — a whole number:

say 'order 66' ~~ / \d+ /; # 「66」

Practice

Complete the quiz that covers the contents of this topic.

Course navigation

Quantifiers   |   Quiz — Basic quantifiers


💪 Or jump directly to the exercises in this section.