Course of Raku / Regexes and grammars / Regexes / Lookaround assertions / Exercises / Between brackets
Solution: Between brackets
Here is a possible solution to the task.
Code
say '$50' ~~ / <?after '$'> \d+ >> <!before '.'> /;🦋 You can find the source code in the file percent-number.raku.
Output
「50」Comments
<?after '$'>is a positive lookbehind — it requires a$just before the number — and<!before '.'>is a negative lookahead — it requires that a.does not follow. Neither the$nor the surroundings become part of the match, so the result is just50.The
>>is a word boundary marking the end of the number. Without it, greedy\d+could backtrack: on$39.99it would give up the9and match3(which is not followed by.).>>forces the whole number to be taken, so$3.99and$39.99correctly match nothing.This is a case where a lookahead earns its keep: you cannot express “not followed by a decimal point” with an ordinary capturing group, because there is nothing there to capture — only a condition to check.
Course navigation
← Between brackets | Adverbs →