Course of Raku / Addendum 🆕 / Types and text machines / Regexes and grammars / Exercises / Normalise whitespace

Solution: Normalise whitespace

Here is a possible solution to the task.

Code

my $messy = '  too    many     spaces   ';

say $messy.trim.subst(/\s+/, ' ', :g);

🦋 You can find the source code in the file normalize-whitespace.raku.

Output

too many spaces

Comments

  1. .trim removes the leading and trailing spaces; the substitution then replaces every run of whitespace \s+ with one space.

  2. The :g adverb makes the substitution global, so all the gaps are collapsed, not just the first.

Course navigation

Normalise whitespace   |   Validate identifiers