Course of Raku / Regexes and grammars / Grammars / Creating grammars / Exercises / Parse a full name

Solution: Parse a full name

Here is a possible solution to the task.

Code

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

say FullName.parse('Grace Hopper')<last>;

🦋 You can find the source code in the file parse-a-pair.raku.

Output

「Hopper」

Comments

  1. TOP describes the whole name; first and last describe its parts, with a literal space between them.

  2. After parsing, each token is a named capture, so the last name is read as <last> on the match object.

Course navigation

Parse a full name   |   Parse a hashtag