Regexes & grammars

Quantifiers, anchors & alternation

Full

The building blocks — + * ? quantifiers, ^ $ anchors, and < a b > alternation.

Beyond literal text and metacharacters like \d, regexes are built from quantifiers (how many), anchors (where), and alternation (which of several).

Quantifiers and anchors #

+ means one-or-more, * zero-or-more, ? zero-or-one. ^ and $ anchor to the start and end of the string, so ^ a+ $ means "nothing but as".

say so "aaa" ~~ /^ a+ $/;
say so "" ~~ /^ a+ $/;
Output
True
False

"aaa" is all as so it matches; the empty string fails because + needs at least one.

Alternation with < … > #

A quoted word list < cat dog > matches any one of its alternatives — a concise literal alternation.

for <cat dog fish> {
    say "$_: ", (/^ < cat dog > $/ ?? "pet" !! "other");
}
Output
cat: pet
dog: pet
fish: other

Notes #