Course of Raku / Regexes and grammars / Regexes / Quantifiers / Exercises / Two to four digits
Solution: Two to four digits
Here is a possible solution to the task.
Code
say 'abc12345' ~~ / \d ** 2..4 /;🦋 You can find the source code in the file three-digits.raku.
Output
「1234」Comments
\d ** 2..4matches between two and four digits in a row.The string has five digits available, but the range caps the match at four, so the pattern takes
1234and leaves the final5. Being greedy, it takes the most the range permits rather than the fewest.Greed only applies within a single match — the engine still stops at the first place the pattern succeeds. Even if a longer digit sequence appears later in the string, it is never reached:
say 'abc123def6789012z' ~~ / \d ** 2..4 /; # 「123」Here
123is matched even though the later run6789012would have filled the whole range with6789. The leftmost match wins.