Course of Raku / Regexes and grammars / Grammars / Creating grammars / Exercises / Parse a time
Solution: Parse a time
Here is a possible solution to the task.
Code
grammar Time {
token TOP { <hour> ':' <minute> ':' <second> }
token hour { \d+ }
token minute { \d+ }
token second { \d+ }
}
say Time.parse('09:30:45')<second>;🦋 You can find the source code in the file parse-a-time.raku.
Output
「45」Comments
TOPdescribes the whole time as three digit tokens separated by colons.After parsing, each token is a named capture, so the second is read as
<second>on the match. Adding a third part is just one more token and one more colon — the grammar scales naturally.
Course navigation
← Parse a time | Tokens and rules →