3.8. Using Character Classes

Character classes are simply a form of alternation (specification of alternative possibilities) where each submatch is a single character. In the simplest case, we list a set of characters inside square brackets:

/[aeiou]/    # Match any single letter a, e, i, o, u; equivalent
             # to /(a|e|i|o|u)/ except for group-capture

Inside a character class, escape sequences such as \n are still meaningful, but metacharacters such as . and ? do not have any special meanings:

/[.\n?]/     # Match any of: period, newline, question mark

The caret (^) has special meaning inside a character class if used at the beginning; it negates the list of characters (or refers to their complement):

[^aeiou]     # Any character EXCEPT a, e, i, o, u

The hyphen, ...

Get The Ruby Way: Solutions and Techniques in Ruby Programming, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.