Course of Raku / Regexes and grammars / Regexes / Captures / Exercises / Initial and surname

Solution: Initial and surname

Here is a possible solution to the task.

Code

if 'J Smith' ~~ / $<initial>=(\w) ' ' $<surname>=(\w+) / {
    say ~$<surname>;
}

🦋 You can find the source code in the file initial-and-surname.raku.

Output

Smith

Comments

  1. $<initial>=(\w) captures a single word character; $<surname>=(\w+) captures the run of letters after the space.

  2. The surname is then read back by name as $<surname>, and the ~ prefix prints it as a plain string; without it, say $<surname> would show the match object as 「Smith」.

Course navigation

Initial and surname   |   Alternations