Skip to main content

Character Classes and Quantifiers

Character Classes Fundamentals

0:00
LearnStep 1/3

Square Bracket Notation

Square Bracket Notation

In regular expressions, a character class (or set) allows you to tell the regex engine to match only one out of several characters. This is done by placing the characters inside square brackets [].

Basic Usage

If you want to match the word "grey" or "gray", you can use gr[ea]y. This tells Python to match 'g', 'r', then either 'e' or 'a', and finally 'y'.

python

Character Ranges

Listing every character you want to match can be tedious. You can use a hyphen - to define a range of characters.

  • [0-9]: Matches any single digit from 0 to 9.
  • [a-z]: Matches any lowercase letter from a to z.
  • [A-Z]: Matches any uppercase letter from A to Z.
  • [A-Za-z]: Matches any letter (uppercase or lowercase).
python