...

/

More on Character Classes (Regex)

More on Character Classes (Regex)

This lesson discusses the character classes of regular expressions in detail.

Complement of a character class

So far, we’ve used character classes like [aeiou] (listing all allowed characters literally) and [a-z] (specifying a range of characters).

There’s more to these.

We can negate classes by prepending a not character (^) inside the square brackets. For example, [^AEIOUaeiou] allows every character that’s not a vowel. So, we can find all words that don’t start with a vowel:

Press + to interact
Ruby
text = "A regular expression is a sequence of characters that define a search pattern."
p text.scan(/\b[^AEIOUaeiou ][^ ]*\b/)

This starts at a word boundary and allows everything that’s not a vowel or a space as a first character, when it’s optionally followed by one or many characters that aren’t a space, followed by a word boundary.

Predefined classes

Regular expressions also come ...