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 ** 2 }
token minute { \d ** 2 }
token second { \d ** 2 }
}
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 tokens separated by colons. Each part is\d ** 2— exactly two digits — rather than an open-ended\d+, so a malformed value like09:30:456is rejected. (If a part may be unpadded, such as the hour in9:30:45, write\d ** 1..2to allow one or two digits.)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 →