Course of Raku / Regexes and grammars / Regexes / Captures / Exercises / City and country

Solution: City and country

Here is a possible solution to the task.

Code

if 'London-UK' ~~ / $<city>=(\w+) '-' $<country>=(\w+) / {
    say ~$<city>;
    say ~$<country>;
}

🦋 You can find the source code in the file name-and-age.raku.

Output

London
UK

Comments

  1. $<city>=( … ) and $<country>=( … ) give the two captures names instead of numbers.

  2. After the match they are read back as $<city> and $<country>, which reads more clearly than $0 and $1 would.

  3. The ~ prefix puts each capture into string context so it prints as plain text; without it, say $<city> would show the match object as 「London」.

Course navigation

City and country   |   Last name first