Basic

Anchors and edges

A search finds a match anywhere. Anchors pin the pattern to a place, and that pin is the difference between a loose check and a real rule.

What you will see

True

About 2 min of reading

Try It

Check what an anchor pins.

1

Start pinned.

import re print(bool(re.search("^cat", "the cat")))

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

What it prints
False
2

End pinned.

import re print(bool(re.search("cat$", "the cat")))

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

What it prints
True
3

Word edge.

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

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

What it prints
False
4

Full match.

import re print(bool(re.fullmatch("c.t", "cat")))

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

What it prints
True

Data Flow

An anchor tests a position instead of a character, so the engine either continues at that spot or gives up.
1 reach an anchor
↓
2 test the position
↓
3 continue at that spot
↓
4 give up on a 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("^cat", "the cat"))) False
Why this works
A rule needs edges

A check that passes inside a longer string is not a rule about the string. Pin both ends when the whole value matters.

Trailing spaces

An anchored pattern fails on trailing whitespace. Trim the input or allow the space in the pattern.

Examples

Start of text

import re
print(bool(re.search("^cat", "the cat")))

The caret pins the pattern to the start. This fails since cat sits later.

End of text

import re
print(bool(re.search("cat$", "the cat")))

The dollar pins the pattern to the end. Trailing spaces break this.

Word edge

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

A word edge is where a word character meets a non word one. This fails inside a longer word.

Whole line only

import re
print(bool(re.fullmatch("c.t", "cat")))

fullmatch needs the entire text to fit. It is anchors at both ends written once.

Anchors and lines

import re
print(len(re.findall("^a", "a\na", re.MULTILINE)))

Multiline makes the caret match after every newline.

Anchors cost nothing

import re
print(bool(re.search("^\d", "4x")))

An anchor checks a position, not a character. It adds no backtracking.

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.

← Repeating parts
Previous Lesson
Repeating parts
Next Lesson
Groups and captures
Groups and captures →