Course of Raku / Regexes and grammars / Regexes / Literals and character classes
Character classes
Often you do not want to match one fixed character but any character
out of a set. Such a set is called a character class and is
written between <[ and ]>:
say 'grey' ~~ / gr <[ae]> y /; # 「grey」
say 'gray' ~~ / gr <[ae]> y /; # 「gray」The class <[ae]> matches a single character that
is either a or e, so both spellings of the
colour — or color, if you prefer — match.
Inside the brackets you can list a range with two dots:
say 'a1b2' ~~ / <[0..9]> /; # 「1」<[0..9]> matches any one digit; the first digit in
the string is 1.
To match any character that is not in the set, put a minus sign right after the opening bracket:
say 'stop!' ~~ / <-[a..z]> /; # 「!」Here <-[a..z]> matches the first character that is
not a lowercase letter, which is the exclamation mark.
You can combine several pieces in one class. For example,
<[a..z A..Z 0..9]> matches a letter or a digit. The
spaces there are only for readability — as everywhere in a regex, spaces
inside <[…]> are ignored, so
<[a..zA..Z0..9]> is exactly the same class.
Practice
Complete the quiz that covers the contents of this topic.
Course navigation
← Matching literal text | Quiz — Custom classes →
💪 Or jump directly to
the exercises in this section.