Course of Raku / Addendum 🆕 / Types and text machines / Regexes and grammars / Exercises / Extract and sum numbers

Solution: Extract and sum numbers

Here is a possible solution to the task.

Code

my $text = 'order 12 apples, 3 pears and 25 plums';

my @numbers = $text.comb(/\d+/);

say "numbers: @numbers[]";
say "sum: { [+] @numbers }";

🦋 You can find the source code in the file extract-numbers.raku.

Output

numbers: 12 3 25
sum: 40

Comments

  1. Passing the regex /\d+/ to .comb returns every run of digits as a separate string, ignoring the words in between.

  2. [+] @numbers adds them up, coercing the digit strings to numbers along the way.

Course navigation

Extract and sum numbers   |   Parse a date with named captures