Course of Raku / Regexes and grammars / Grammars / Tokens and rules / Exercises / Regex versus token
Solution: Regex versus token
Here is a possible solution to the task.
Code
my regex r { \d+ '5' }
my token t { \d+ '5' }
say so '12345' ~~ / <r> /;
say so '12345' ~~ / <t> /;🦋 You can find the source code in the file token-instead.raku.
Output
True
FalseComments
In the
regex,\d+first grabs all of12345, then backtracks — giving back the final5so the literal5can match. So the regex succeeds.The
tokenrefuses to give anything back:\d+keeps all of12345, the literal5finds nothing left, and the token fails. This non-backtracking behaviour is exactly whytokenis the right default inside grammars.