Basic

Case and flags

The same pattern behaves differently per task. Flags change how the engine reads the pattern, and forgetting one changes results quietly.

What you will see

2

About 1 min of reading

Try It

Check what a flag changes.

1

Case ignored.

import re print(bool(re.search("cat", "The Cat", re.IGNORECASE)))

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

What it prints
True
2

Line starts.

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

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

What it prints
2
3

Dot crosses.

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

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

What it prints
True
4

Matches counted.

import re print(len(re.findall("a", "Aa", re.IGNORECASE)))

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

What it prints
2

Data Flow

Flags are read before the pattern runs, then change how characters and positions are compared.
1 read the flags
↓
2 parse the pattern
↓
3 compare with the flag
↓
4 report the result
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", re.IGNORECASE))) True
Why this works
Flags are per call

A flag passed once applies to that call only. A compiled pattern is where flags belong when a pattern is reused.

A silent difference

Ignoring case changes which text matches. A test written without the flag can pass while the real run fails.

Examples

Ignore case

import re
print(bool(re.search("cat", "The Cat", re.IGNORECASE)))

The flag makes letters match either case. Without it the capital fails.

Multiline caret

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

Multiline makes the caret match at every line start.

Dot matches newline

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

Dotall lets the dot cross a newline. Without it the dot stops at one.

Compile once

import re
pat = re.compile("a+", re.IGNORECASE)
print(bool(pat.search("AA")))

A compiled pattern keeps its flags. Reusing it skips the parse on each call.

Flag in the pattern

import re
print(bool(re.search("(?i)CAT", "cat")))

An inline flag applies from that point on. Put it first to cover all of it.

Flags change counts

import re
print(len(re.findall("a", "Aa", re.IGNORECASE)))

The count doubles when case is ignored. A count check must know the flag.

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.

← Groups and captures
Previous Lesson
Groups and captures
Next Lesson
Greedy and lazy
Greedy and lazy →