Basic

Groups and captures

A group marks part of a pattern as one unit. That mark lets you repeat the unit and take the text out of a match, which is how parsing works.

What you will see

b

About 2 min of reading

Try It

Check what a group captures.

1

Number captured.

import re hit = re.search("(\d+)px", "12px") print(hit.group(1))

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

What it prints
12
2

Group repeated.

import re print(bool(re.search("(ab)+", "ababab")))

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

What it prints
True
3

Branch choice.

import re print(bool(re.search("cat|dog", "a dog")))

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

What it prints
True
4

Second group.

import re hit = re.search("(a)(b)", "ab") print(hit.group(2))

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

What it prints
b

Data Flow

Each opening bracket starts a capture, the part inside is remembered, and the numbers are handed out in bracket order.
1 open a group
↓
2 match the part
↓
3 remember the text
↓
4 hand out the number
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
hit = re.search("(\d+)px", "12px") sets nothing on screen
print(hit.group(1)) 12
Why this works
Brackets do two jobs

A group both limits a repetition and names a piece to take out. Forgetting one job gives a pattern that matches but cannot be parsed.

Order of branches

The pipe reaches the widest span unless grouped. Group the alternatives when the choice is part of a longer pattern.

Examples

Capture a part

import re
hit = re.search("(\d+)px", "12px")
print(hit.group(1))

Parentheses mark a part. Group one is the text inside the first pair.

Repeat a unit

import re
print(bool(re.search("(ab)+", "ababab")))

A group is one unit, so a repetition applies to the whole thing.

Choose a branch

import re
print(bool(re.search("cat|dog", "a dog")))

A pipe offers alternatives. The bar has the lowest priority, so a group narrows it.

Numbered groups

import re
hit = re.search("(a)(b)", "ab")
print(hit.group(2))

Groups are numbered by their opening brackets from the left.

No capture wanted

import re
hit = re.search("(?:ab)+", "abab")
print(hit.group(0))

A question mark colon marks a group that groups but does not capture.

Groups in a swap

import re
out = re.sub("(\w+) (\w+)", "\2 \1", "first last")
print(out)

Group text can be put back in a different order. That is how fields get reordered.

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.

← Anchors and edges
Previous Lesson
Anchors and edges
Next Lesson
Case and flags
Case and flags →