Regexes & grammars

Named regexes as subrules

Full

Define reusable patterns with my token / my regex and call them as <name>.

A pattern can be given a name with my token or my regex, then invoked inside another regex as <name> — a subrule. The submatch is captured under that name, readable as $<name>. This is the same mechanism grammars use, at a smaller scale.

A named token #

token is the non-backtracking form (the usual default). Call it with <name> and read its match from $<name>.

my token num { \d+ }
say so "x42y" ~~ /<num>/;
say ~$<num>;
Output
True
42

A named regex #

regex is the backtracking form; otherwise it works the same as a subrule.

my regex id { <[a..z]>+ }
"hello123" ~~ /<id>/;
say ~$<id>;
Output
hello

<id> matches the leading lowercase run hello, stopping at the first digit.

Notes #