Regexes & grammars

Captures

Full

Pull pieces out of a match — positional $0, $1, … and named $<name>.

Parentheses in a regex capture the text they match. Positional groups land in $0, $1, … (in order of their opening paren); named groups land in $<name>.

Positional captures #

if "2026-07-19" ~~ /(\d+) "-" (\d+) "-" (\d+)/ {
    say "$0 / $1 / $2";
}
Output
2026 / 07 / 19

Each ( … ) becomes the next $n, counting from zero.

Named captures #

$<name>=( … ) labels a capture, which reads back as $<name>. Named captures make the match self-documenting and order-independent.

if "John 42" ~~ / $<name>=(\w+) \s+ $<age>=(\d+) / {
    say ~$<name>;
    say ~$<age>;
}
Output
John
42

Notes #