Basic

Repeating parts

Text has runs of unknown length. Repetition marks say how many times a part may repeat, which is what lets one pattern cover every length.

What you will see

True

About 2 min of reading

Try It

Check what a repetition allows.

1

Runs found.

import re print(len(re.findall("ab*", "a ab abb")))

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

What it prints
3
2

Plus needs one.

import re print(bool(re.search("\d+", "no digits")))

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

What it prints
False
3

Optional spelling.

import re print(bool(re.search("colou?r", "color")))

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

What it prints
True
4

Exact count.

import re print(bool(re.search("\d{4}", "12345")))

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

What it prints
True

Data Flow

A repetition tries the longest run first, then gives characters back one at a time until the rest of the pattern fits.
1 reach a repetition
↓
2 take the longest run
↓
3 try the rest
↓
4 give back on a failure
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(len(re.findall("ab*", "a ab abb"))) 3
Why this works
Repetition is greedy by default

A repetition takes as much as it can and gives back only when the rest fails. That is what makes a wide match grab too much.

A run of unknown length

A pattern with a plus can match at many lengths. Anything that assumes one length is wrong.

Examples

Zero or more

import re
print(len(re.findall("ab*", "a ab abb")))

The star means zero or more of the part before it. Three runs match here.

One or more

import re
print(bool(re.search("\d+", "no digits")))

The plus needs at least one. This fails where the star would succeed.

Optional

import re
print(bool(re.search("colou?r", "color")))

The question mark makes the character before it optional.

Exact count

import re
print(bool(re.search("\d{4}", "12345")))

Braces give an exact count. Four digits fit inside a longer run.

A range of counts

import re
print(bool(re.search("\d{2,3}", "1")))

Two to three digits needed, one given. The count is the smallest match.

Repeat a group

import re
print(bool(re.search("(ab){2}", "abab")))

Braces after a group repeat the whole group, not one character.

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.

← Character classes
Previous Lesson
Character classes
Next Lesson
Anchors and edges
Anchors and edges →