Course of Raku / Regexes and grammars / Grammars / Creating grammars / Exercises / Parse a hashtag
Solution: Parse a hashtag
Here is a possible solution to the task.
Code
grammar Hashtag {
token TOP { '#' <tag> }
token tag { \w+ }
}
say Hashtag.parse('#raku')<tag>;🦋 You can find the source code in the file parse-hashtag.raku.
Output
「raku」Comments
TOPspells out the fixed#followed by the<tag>token..parserequires the whole string to match, and the tag is then available as the<tag>capture.
An alternative
You can instead let tag match the whole hashtag — the
# together with the word — and reach the word through a
nested word rule:
grammar Hashtag {
token TOP { <tag> }
token tag { '#' <word> }
token word { \w+ }
}
say Hashtag.parse('#raku')<tag><word>;This prints the same 「raku」. Now
<tag> captures the entire #raku, while
the word inside it is reached as <tag><word>.
The grammar reads a little more like the thing it describes — a hashtag
is a # followed by a word, and the word is a named
piece in its own right.
Course navigation
← Parse a hashtag | Parse a time →