Regular Expressions For Regular Folk

Character Classes

It’s possible to match a character from within a set of characters.

/[aeiou]/g
  • 4 matchesavocado
  • 2 matchesbrinjal
  • 3 matchesonion
  • 0 matchesrhythm

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

Here’s another example of these in action:

/p[aeiou]t/g
  • 1 matchpat
  • 1 matchpet
  • 1 matchpit
  • 1 matchspat
  • 2 matchesspot a pet
  • 0 matchesbat

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.

/[a-z]/g
  • 5 matchesjohn_s
  • 5 matchesmatej29
  • 5 matchesAyesha?!
  • 0 matches4952
  • 0 matchesLOUD
Warning

The regex /[a-z]/g matches only one character. In the example above, the strings have several matches each, each one character long. Not one long match.

We can combine ranges and individual characters in our regexes.

/[A-Za-z0-9_-]/g
  • 6 matchesjohn_s
  • 7 matchesmatej29
  • 6 matchesAyesha?!
  • 4 matches4952
  • 4 matchesLOUD

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:

/[^aeiou]/g
  • 6 matchesUmbrella
  • 6 matchescauliflower
  • 0 matchesou

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 a, e, i, o, and u

Examples

Prohibited username characters

/[^a-zA-Z_0-9-]/g
  • 0 matchesTheLegend27
  • 0 matchesWaterGuy12
  • 0 matchesSmokie_Bear
  • 7 matchesRobert'); DROP TABLE Students;--

Unambiguous characters

/[A-HJ-NP-Za-kmnp-z2-9]/g
  • 1 matchfoo
  • 2 matcheslily
  • 0 matcheslI0O1
  • 11 matchesunambiguity