Course of Raku / Addendum 🆕 / Types and text machines / Regexes and grammars / Exercises / Validate identifiers

Solution: Validate identifiers

Here is a possible solution to the task.

Code

for <count total2 2fast my-var _hidden> -> $name {
    my $ok = $name ~~ / ^ <[A..Za..z_]> <[A..Za..z0..9_]>* $ /;

    say "$name: { $ok ?? 'valid' !! 'invalid' }";
}

🦋 You can find the source code in the file validate-identifier.raku.

Output

count: valid
total2: valid
2fast: invalid
my-var: invalid
_hidden: valid

Comments

  1. The anchors ^ and $ force the pattern to cover the whole string, so a single stray character like the hyphen in my-var makes it invalid.

  2. The first character class allows a letter or underscore; the second, repeated with *, additionally allows digits — matching the identifier rule exactly.

Course navigation

Validate identifiers   |   A grammar for full names