Course of Raku / Regexes and grammars / Regexes / Captures / Exercises / Split a filename

Solution: Split a filename

Here is a possible solution to the task.

Code

if 'report.txt' ~~ / (\w+) '.' (\w+) / {
    say ~$0;
    say ~$1;
}

🦋 You can find the source code in the file capture-the-year.raku.

Output

report
txt

Comments

  1. The first pair of brackets captures the base name into $0, the second captures the extension into $1. The dot between them is quoted so it matches a literal . rather than any character.

  2. The ~ in front of each capture puts it into string context, so it prints as plain text. Plain say $0 would instead show the match object with its corner brackets, 「report」. Writing say $0.Str does the same as say ~$0.

Course navigation

Split a filename   |   City and country