Course of Raku / Addendum 🆕 / Types and text machines / Regexes and grammars / Exercises / A grammar for full names

Solution: A grammar for full names

Here is a possible solution to the task.

Code

grammar FullName {
    token TOP   { <first> \s+ <last> }
    token first { \w+ }
    token last  { \w+ }
}

my $match = FullName.parse('Grace Hopper');

say ~$match<first>;
say ~$match<last>;

🦋 You can find the source code in the file grammar-fullname.raku.

Output

Grace
Hopper

Comments

  1. The TOP token is where parsing starts; it refers to the other tokens by name with <first> and <last>, which become keys on the match.

  2. $match<first> is a match object; the prefix ~ stringifies it to the plain matched text.

Course navigation

A grammar for full names   |   A grammar that adds