Course of Raku / Regexes and grammars / Grammars / What is a grammar / Exercises / A named token

Solution: A named token

Here is a possible solution to the task.

Code

my regex word { \w+ }

if 'hello world' ~~ / <word> / {
    say $<word>;
}

🦋 You can find the source code in the file named-token.raku.

Output

「hello」

Comments

  1. my regex word { \w+ } gives the pattern a name so it can be reused.

  2. Writing <word> in the pattern matches it and captures the result under the same name, reachable as $<word>. The first run of word characters is hello.

Course navigation

A named token   |   Reuse a token