Skip to content

Latest commit

 

History

History
72 lines (52 loc) · 2.02 KB

character-classes.mdx

File metadata and controls

72 lines (52 loc) · 2.02 KB

import Example from "../src/components/example";

Character classes

It's possible to match a character from one of several characters. Here's an example:

avocado brinjal onion rhythm

Our regex /[aeiou]/g matches all vowels in our input strings.

Here's another example of these in action:

pat pet pit spat spot a pet bat

We match a p, followed by one of the vowels, followed by a t.

There's an intuitive shortcut for matching a character from within a continuous range.

john_s matej29 Ayesha?! 4952 LOUD

We can combine ranges and individual characters in our regexes.

john_s matej29 Ayesha?! 4952 LOUD

Our regex /[A-Za-z0-9_-]/g matches a single character, which must be (at least) one of the following:

  • from A-Z
  • from a-z
  • from 0-9
  • one of _ and -.

We can also "negate" these rules:

Umbrella cauliflower ou

The only difference between the first regex of this chapter and /[^aeiou]/g is the ^ immediately after the opening bracket. Its purpose is to negate the rules defined within the brackets. We are now saying:

"match any character that is not any of «blah», «blah» or «blah».

… instead of:

"match any character that is at least one of «blah», «blah» and «blah»"

Here, «blah» is either an individual character or a range of characters.