Basic

Character classes

A class is a set of characters you allow. Naming the set is shorter than listing every case, and it stops a pattern from matching the wrong shape.

What you will see

True

About 2 min of reading

Quick check

Before this new lesson, one small question about the lesson you just finished. Recall it, do not look it up.

Try It

Check what a class allows.

1

Three digits found.

import re print(bool(re.search("\d\d\d", "abc 415 x")))

Before you run it, say out loud what it will print. Then open the answer.

What it prints
True
2

Set letter found.

import re print(bool(re.search("[abc]", "xyz a")))

Before you run it, say out loud what it will print. Then open the answer.

What it prints
True
3

Range letter.

import re print(bool(re.search("[a-c]", "q")))

Before you run it, say out loud what it will print. Then open the answer.

What it prints
False
4

Not a digit.

import re print(bool(re.search("[^0-9]", "abc")))

Before you run it, say out loud what it will print. Then open the answer.

What it prints
True

Data Flow

Each class is checked against one character at a time, so a run of classes walks the text one step per class.
1 read one character
↓
2 test it against the class
↓
3 move to the next class
↓
4 fail on the first miss
Line by line

Read the first example one line at a time. A line that prints shows what appears on screen; the rest set things up quietly.

import re sets nothing on screen
print(bool(re.search("\d\d\d", "abc 415 x"))) True
Why this works
Classes save cases

One class stands for a whole set. Writing the set out is longer and easy to get wrong when the set grows.

A caret changes meaning

A caret at the start of a set means the opposite set. Anywhere else it means itself.

Examples

Digits only

import re
print(bool(re.search("\d\d\d", "abc 415 x")))

The digit class matches one number character. Three of them match a three digit run.

A set of letters

import re
print(bool(re.search("[abc]", "xyz a")))

Square brackets allow any one of the listed characters.

A range

import re
print(bool(re.search("[a-c]", "q")))

A dash inside the brackets is a range, so a to c covers three letters.

Not a set

import re
print(bool(re.search("[^0-9]", "abc")))

A caret first means not. This matches any character that is not a digit.

A literal dot

import re
print(bool(re.search("\.", "a.b")))

A backslash makes a special character mean itself. Without it the dot matches any character.

A space is a class

import re
print(bool(re.search("\s", "a b")))

The space class covers space, tab and newline. A plain space covers only one.

Words this lesson uses

Each one is defined here on this site. Open the entry for the full definition and the other words it points at.

← What a pattern is
Previous Lesson
What a pattern is
Next Lesson
Repeating parts
Repeating parts →