🐍 Python for Everyone

← Back to all chapters

Chapter 18 of 27 Intermediate 80 min read

Regular Expressions

Every chapter so far has checked text with tools like .startswith(), in, or a chain of if/elif conditions on strings. That works fine for exact, fixed text — but "does this look like a valid email address?" or "pull every phone number out of this messy paragraph" isn't a fixed-text question at all, it's a pattern question. This chapter introduces regular expressions (regex): a mini-language, built into Python's re module, for describing text patterns instead of exact text — the same tool that powers real form validation, log parsing, and data extraction across the industry.

How to read this chapter

Picture a hiring tool that needs to scan hundreds of resumes for a candidate's email address and phone number, buried somewhere in a wall of unstructured text with no fixed format. "email:" in resume_text and .split() can't describe "something that looks like an email address" — there's no fixed string to search for, only a shape: some characters, an @, more characters, a dot, a few letters. Regular expressions exist precisely to describe shapes like that, and this chapter builds up the exact pattern syntax needed to do it.
Sub-topic 1 of 7

1. What a regular expression is

At a glance
  • A regular expression is a mini-language for describing a pattern of text, not one exact string.
  • Python's built-in re module provides the functions that test a pattern against real text.
  • re.match(), re.search(), and re.fullmatch() all check for a pattern, but at different positions in the string.
Why this matters: almost every later sub-topic in this chapter is just richer syntax for the pattern string itself — the three functions here are how that pattern actually gets checked against real text.
What is... a regular expression? A regular expression (often shortened to "regex") is a string written in a special pattern syntax that describes a shape of text, rather than one exact sequence of characters — "three digits, a dash, four digits" instead of the literal text "555-1234". Python's re module (import re) is what actually tests a pattern against a real string.

Start with the import every example in this chapter needs, then the simplest possible check — does a pattern appear anywhere in a string?

match_search_fullmatch_demo.py
import re

text = "Contact us at support@example.com for help."

match_result = re.match(r"support", text)
print(match_result)

search_result = re.search(r"support", text)
print(search_result)

email_pattern = r"support@example\.com"
full_result = re.fullmatch(email_pattern, text)
print(full_result)

full_result_2 = re.fullmatch(email_pattern, "support@example.com")
print(full_result_2)
actual output of match_search_fullmatch_demo.py
None
<re.Match object; span=(14, 21), match='support'>
None
<re.Match object; span=(0, 19), match='support@example.com'>

Each of the three functions checks the pattern against the string in a different place. re.match() only looks right at the very start of the string — since text starts with "Contact", not "support", it finds nothing and returns None.

re.search() found "support" starting at index 14, since it's allowed to look anywhere in the string. re.fullmatch() against the whole sentence found nothing, because the sentence has more text around the email address — but against the bare email address string by itself, with nothing else in it, re.fullmatch() succeeded. This is exactly why fullmatch() is the right choice for form validation: "is this input, in its entirety, a valid email address?" is a fullmatch question, not a search question.

What is... a Match object? A successful call to match(), search(), or fullmatch() returns a Match object (truthy in an if check) holding details about what matched and where; a failed call returns None (falsy), which is why if re.search(...): is the standard way to test "did this pattern appear at all?"

The difference between match() and search() matters most on real, messy text where the pattern isn't at position 0:

match_vs_search_demo.py
import re

text = "Call 555-1234 now"

match_result = re.match(r"\d{3}-\d{4}", text)
print(match_result)

search_result = re.search(r"\d{3}-\d{4}", text)
print(search_result)
print(search_result.group())
actual output of match_vs_search_demo.py
None
<re.Match object; span=(5, 13), match='555-1234'>
555-1234

re.match() returns None here even though the phone number genuinely exists in the string — it just isn't at position 0, and match() refuses to look anywhere else. re.search() finds it fine, and calling .group() on the resulting Match object returns the actual matched text as a plain string. \d and {3} are pattern syntax covered in full in Sub-topic 3 — for now, just notice that search() is almost always the right default when scanning real text for a pattern that could be anywhere.

try_it.py
Click "Run Code" — try changing the text to remove all digits.
Go Deeper: why not just use string methods for everything?

.startswith(), .endswith(), and in are still the right tool when checking for one exact, fixed piece of text — they're simpler and faster than regex for that job. Regex earns its complexity specifically when the thing being checked for is a pattern rather than one fixed string: "any sequence of digits," "something shaped like an email," "one or more spaces." Reach for re only once a plain string method genuinely can't express what's being searched for.

Quick recap
  • A regular expression describes a pattern of text, not one exact string, and Python's re module tests patterns against real strings.
  • re.match() checks only at the start of the string; re.search() checks anywhere; re.fullmatch() requires the whole string to match.
  • A successful match returns a truthy Match object with a .group() method; a failed one returns None.
Sub-topic 2 of 7

2. Finding every match: findall() & finditer()

At a glance
  • re.findall() returns every match in a string as a plain list of strings.
  • re.finditer() returns every match as an iterator of Match objects, giving access to each match's position too.
  • Both scan the entire string, unlike match()/search(), which stop at the first hit.
Why this matters: Sub-topic 1's functions only ever report the first match (or none). Real text — a log file, a resume, a paragraph of user input — usually has a pattern appearing many times, and these two functions are how every occurrence gets pulled out at once.

A log line with several timestamps shows the difference clearly:

What is... findall() vs. finditer()? re.findall(pattern, text) returns a plain list of strings — one per match, in order. re.finditer(pattern, text) returns an iterator of Match objects — slightly more setup to loop over, but each one carries its start/end position, not just the matched text.
findall_finditer_demo.py
import re

log_line = "Errors at 10:15, 10:42, and 11:03 -- three total."

times = re.findall(r"\d{2}:\d{2}", log_line)
print(times)

for match in re.finditer(r"\d{2}:\d{2}", log_line):
    print(match.group(), match.start(), match.end())
actual output of findall_finditer_demo.py
['10:15', '10:42', '11:03']
10:15 10 15
10:42 17 22
11:03 28 33

findall() hands back exactly what's usually wanted — a plain list of the three matched timestamps, ready to loop over, count, or store. finditer() takes one extra step (a for loop instead of printing the result directly) but pays it back with .start() and .end() on each match — the exact character positions where that match was found in the original string, which findall() throws away.

  • Reach for findall() when only the matched text itself is needed.
  • Reach for finditer() when the match's position in the string matters too, or when the pattern has groups (Sub-topic 4) and each match needs individual inspection.
try_it.py
Click "Run Code" — try adding another "SKU-####" to the text.
Go Deeper: findall() with a pattern that has no matches

If nothing in the string matches the pattern, findall() returns an empty list [] rather than None — useful, since checking if matches: or len(matches) works the same way it would for any other list, with no special None-handling needed first.

Quick recap
  • findall() returns every match as a list of plain strings.
  • finditer() returns every match as an iterator of Match objects, with position info via .start()/.end().
  • Both scan the whole string for every occurrence, not just the first.
Sub-topic 3 of 7

3. Character classes, quantifiers & anchors

At a glance
  • A character class like [aeiou] or the shorthand \d matches one character from a set.
  • A quantifier like *, +, ?, or {m,n} says how many times the thing before it can repeat.
  • An anchor like ^ or $ matches a position (start/end of string), not a character.
Why this matters: these three ingredients are the actual vocabulary of a regex pattern — everything from Sub-topic 1's \d{3}-\d{4} phone-number pattern to a real email or resume-scanning pattern is built entirely out of character classes, quantifiers, and anchors strung together.

A character class matches exactly one character, chosen from a set — either written out explicitly or as one of a few common shorthands:

What is... a character class? A character class, written [...], matches any one character from the set inside the brackets — [aeiou] matches one vowel, [A-Z] matches one uppercase letter. Python's re module also has shorthand classes: \d (any digit), \w (any letter, digit, or underscore), and \s (any whitespace character).
character_classes_demo.py
import re

print(re.findall(r"[aeiou]", "hello world"))
print(re.findall(r"[A-Z][a-z]+", "Alice met Bob and Carol"))
print(re.findall(r"\d+", "order 12 has 345 items"))
actual output of character_classes_demo.py
['e', 'o', 'o']
['Alice', 'Bob', 'Carol']
['12', '345']

[aeiou] found every individual vowel character in "hello world" — each match is exactly one character. [A-Z][a-z]+ combines a character class with a quantifier (the +, explained next) to find whole capitalized words: one uppercase letter, followed by one or more lowercase letters. \d+ is the shorthand digit class plus the same +, finding runs of one or more digits anywhere in the text.

A quantifier controls how many times whatever comes right before it is allowed to repeat — this is the piece that turns "one character" into "a whole number" or "an optional letter":

quantifier reference
*       zero or more
+       one or more
?       zero or one (optional)
{m}     exactly m times
{m,n}   between m and n times, inclusive
{m,}    m or more times
quantifiers_demo.py
import re

print(re.findall(r"colou?r", "color colour"))
print(re.findall(r"\d{2,4}", "a 5 b 55 c 555 d 5555 e 55555"))

anchored = re.match(r"^\d+$", "42")
print(anchored)
anchored_fail = re.match(r"^\d+$", "42 apples")
print(anchored_fail)
actual output of quantifiers_demo.py
['color', 'colour']
['55', '555', '5555', '5555']
<re.Match object; span=(0, 2), match='42'>
None

colou?r matches both spellings by making the u optional with ?. \d{2,4} matches runs of 2 to 4 digits — notice the 5-digit run "55555" splits into two separate matches, "5555" and then a leftover "5" too short to match on its own (which is why it's missing from the output entirely; a lone digit doesn't satisfy {2,4}'s minimum of 2).

The last two lines introduce anchors — ^ and $ don't match a character at all, they match a position: the very start and very end of the string, respectively. ^\d+$ only succeeds if the entire string, from position 0 to the last character, is nothing but digits — exactly why "42" matches but "42 apples" doesn't, since there's text after the digits that the pattern's $ anchor refuses to allow.

What is... escaping a special character? Characters like ., *, +, and ? have special meaning in a regex pattern. To match one of them literally — an actual period, not "any character" — put a backslash before it: \. matches a literal dot, \* matches a literal asterisk.

. on its own means "any single character" — which makes matching an actual, literal period require escaping it:

escaping_dot_demo.py
import re

print(re.findall(r"c.t", "cat cot c9t c.t"))
print(re.findall(r"3\.14", "pi is 3.14 not 3x14"))
actual output of escaping_dot_demo.py
['cat', 'cot', 'c9t', 'c.t']
['3.14']

Unescaped . in c.t matches any character between c and t — including a literal period, since . means "anything here," not "a dot specifically." 3\.14 escapes the dot, so it only matches an actual decimal point — which is why it finds "3.14" but correctly skips "3x14", which has a different character in that position.

try_it.py
Click "Run Code" — \b marks a word boundary, so \b\d{5}\b matches a standalone 5-digit run.
Go Deeper: greedy quantifiers try to match as much as possible

Every quantifier introduced here (*, +, {m,n}) is greedy by default — it tries to consume as many characters as it possibly can while still letting the rest of the pattern succeed, which is exactly why \d{2,4} grabbed 4 digits at a time instead of stopping at 2. Sub-topic 7 covers the non-greedy versions (*?, +?) and exactly when the difference matters.

Quick recap
  • A character class ([...], \d, \w, \s) matches one character from a set.
  • A quantifier (*, +, ?, {m,n}) controls how many times the preceding piece can repeat.
  • Anchors (^, $) match a position, not a character; special characters like . need a backslash to match literally.
Sub-topic 4 of 7

4. Groups & named groups

At a glance
  • Parentheses (...) create a group — a labeled piece of the overall match, accessible on its own.
  • .group(n) retrieves group number n; .group(0) (or no argument) is the entire match.
  • (?P<name>...) creates a named group, accessed by name via .group("name") or all at once via .groupdict().
Why this matters: so far, a match either succeeds or fails as one whole unit. Groups are how a pattern pulls out specific labeled pieces of what it matched — the year, the month, and the day out of one date, rather than just the date as one undivided blob.

Wrapping part of a pattern in parentheses doesn't change what it matches — it just makes that piece separately retrievable afterward:

What is... a group? A group is a parenthesized part of a pattern, (...). It matches exactly what it would have matched without the parentheses, but the matched text for that piece becomes individually retrievable through the resulting Match object, numbered left to right starting at 1 (group 0 is always the whole match).
groups_demo.py
import re

text = "2026-07-06"
match = re.match(r"(\d{4})-(\d{2})-(\d{2})", text)
print(match.group())
print(match.group(0))
print(match.group(1))
print(match.group(2), match.group(3))
print(match.groups())
actual output of groups_demo.py
2026-07-06
2026-07-06
2026
07 06
('2026', '07', '06')

match.group() and match.group(0) are identical — both return the entire matched text, "2026-07-06". match.group(1) returns just what the first pair of parentheses matched, the year; groups 2 and 3 are the month and day, in the order the parentheses appear in the pattern, left to right. match.groups() is a shortcut that returns every numbered group at once, as a tuple.

Numbered groups work, but group(1), group(2), and group(3) don't say what each piece actually is — a named group fixes that:

What is... a named group? A named group, written (?P<name>...), works exactly like a regular group but can be retrieved by a meaningful name instead of a position number — match.group("year") instead of match.group(1) — which reads far more clearly once a pattern has more than one or two groups in it.
named_groups_demo.py
import re

text = "2026-07-06"
match = re.match(r"(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})", text)
print(match.group("year"))
print(match.group("month"))
print(match.groupdict())
actual output of named_groups_demo.py
2026
07
{'year': '2026', 'month': '07', 'day': '06'}

(?P<year>\d{4}) matches the exact same four digits a plain (\d{4}) would, but now that piece is retrievable as match.group("year") — self-documenting, and immune to breaking if a group gets reordered or a new one gets inserted earlier in the pattern later on. match.groupdict() returns every named group at once as a ready-to-use dictionary, exactly the shape a real program usually wants for structured data pulled out of text.

try_it.py
Click "Run Code" — try changing [ERROR] in log_entry to [WARNING].
Go Deeper: what happens if a group didn't participate in the match?

If part of a pattern is optional (like ? or an alternation) and that optional group never actually matched anything, calling .group() for it returns None rather than an empty string — worth checking for before doing further string operations on a group that might not have matched.

Quick recap
  • Parentheses (...) create a numbered group, retrievable with .group(n); group 0 is always the whole match.
  • (?P<name>...) creates a named group, retrievable with .group("name").
  • .groups() returns every numbered group as a tuple; .groupdict() returns every named group as a dict.
Sub-topic 5 of 7

5. Search-and-replace: re.sub() & re.split()

At a glance
  • re.sub(pattern, replacement, text) replaces every match of pattern in text with replacement.
  • re.split(pattern, text) splits text wherever pattern matches, returning a list of the pieces in between.
  • Both work with patterns, not just fixed strings — str.replace()/str.split() can only do exact-text versions of the same job.
Why this matters: everything so far has only ever read a match out of text. sub() and split() are how a pattern actually changes text — masking sensitive data, or breaking messy input apart on more than one possible separator.

str.replace() only replaces one exact string; re.sub() replaces anything matching a whole pattern, which is the difference that makes it useful for masking a whole category of sensitive data at once:

sub_split_demo.py
import re

text = "Call 555-1234 or 555-5678"
masked = re.sub(r"\d{3}-\d{4}", "XXX-XXXX", text)
print(masked)

sentence = "one,  two,three   four"
parts = re.split(r"[,\s]+", sentence)
print(parts)
actual output of sub_split_demo.py
Call XXX-XXXX or XXX-XXXX
['one', 'two', 'three', 'four']

re.sub() found and replaced both phone numbers in one call, since it applies to every match, not just the first — a fixed-text str.replace("555-1234", "XXX-XXXX") would have needed one call per distinct number, and couldn't have described "any phone number" as a single rule at all.

re.split(r"[,\s]+", sentence) splits on a comma or one or more whitespace characters, in any mix — which is exactly why it correctly handles a comma with no space ("two,three") and multiple spaces ("three four") in the very same call. str.split(",") alone could never have handled both separator styles in one pass, since it only recognizes a single, fixed separator string.

What is... the real-world use for re.sub()? Masking sensitive data (credit card numbers, phone numbers, emails) before logging or displaying it, cleaning up inconsistent whitespace or formatting in scraped or user-submitted text, and normalizing messy input (e.g. collapsing every kind of dash into one standard dash) are all genuinely common re.sub() use cases in real systems.
try_it.py
Click "Run Code" — try changing r"!+" to r"[A-Z]{2,}" and see what happens to the shouted words.
Go Deeper: re.sub() can use captured groups in the replacement

A replacement string can reference groups from the pattern using \1, \2, and so on — useful for rearranging matched text rather than just deleting or masking it, for example turning "07/06/2026" into "2026-07-06" with re.sub(r"(\d{2})/(\d{2})/(\d{4})", r"\3-\1-\2", text). This chapter's exercises and practice bank stick to simpler replacements, but this is worth knowing exists.

Quick recap
  • re.sub(pattern, replacement, text) replaces every match of a pattern, not just one fixed string.
  • re.split(pattern, text) splits on anything matching a pattern, handling multiple separator styles in one call.
  • Both go beyond what str.replace()/str.split() can do, since those only recognize one fixed separator or target string.
Sub-topic 6 of 7

6. Compiled patterns with re.compile()

At a glance
  • re.compile(pattern) turns a pattern string into a reusable compiled pattern object.
  • A compiled pattern has its own .match()/.search()/.findall() methods — same behavior, no need to pass the pattern string again each time.
  • Compiling once and reusing it is faster than passing the same raw pattern string to re.search() repeatedly in a loop.
Why this matters: every example so far has passed a plain pattern string directly to re.match()/re.search()/etc. That's fine for a one-off check, but scanning many lines of a real file with the same pattern is exactly the case re.compile() is built for.

Scanning several lines of text for the same phone-number pattern shows the compiled-pattern workflow directly:

What is... a compiled pattern? re.compile(pattern) processes a pattern string once into a reusable compiled pattern object. Calling .search(), .match(), or .findall() directly on that object works exactly like the module-level re.search(pattern, text) version, just without needing to pass (and re-parse) the pattern string on every single call.
compile_demo.py
import re

phone_pattern = re.compile(r"\d{3}-\d{3}-\d{4}")

lines = [
    "Call 555-123-4567 for support.",
    "No phone number here.",
    "Reach sales at 555-987-6543 today.",
]

for line in lines:
    match = phone_pattern.search(line)
    if match:
        print(match.group())
actual output of compile_demo.py
555-123-4567
555-987-6543

phone_pattern is built once, outside the loop, from re.compile(r"\d{3}-\d{3}-\d{4}"). Inside the loop, calling phone_pattern.search(line) reuses that already-processed pattern against each line — the pattern itself never gets re-parsed on every iteration, only the search against new text happens each time. The second line has no phone number, so phone_pattern.search() correctly returns None and the if match: check skips it.

  • For a pattern used once, plain re.search(pattern, text) is simplest — no need to compile first.
  • For a pattern reused across many lines, files, or calls — exactly the log-scanning and resume-scanning scenarios this chapter keeps returning to — compiling it once with re.compile() is the standard, more efficient approach.
try_it.py
Click "Run Code" — try adding a fourth sentence with two capitalized words.
Go Deeper: re.search() already caches compiled patterns internally

Python's re module actually keeps a small internal cache of recently used patterns, so calling re.search() with the exact same pattern string repeatedly isn't as slow as it might seem. The real benefit of an explicit re.compile() is readability and clarity of intent — a named, reusable pattern object makes it obvious the same pattern is meant to be applied many times — plus it avoids any risk of the cache being evicted under heavy, varied pattern use across a large program.

Quick recap
  • re.compile(pattern) returns a reusable compiled pattern object with its own .search()/.match()/.findall() methods.
  • Compiling once and reusing it is the standard approach when the same pattern gets applied across many lines, files, or calls.
  • For a single one-off check, the plain module-level re.search(pattern, text) form is simpler and perfectly fine.
Sub-topic 7 of 7

7. Gotchas: greedy matching, raw strings & flags

At a glance
  • Greedy quantifiers (*, +) match as much as possible; adding ? after them (*?, +?) makes them non-greedy, matching as little as possible.
  • A pattern string should almost always be a raw string (r"...") — without it, Python's own string-escaping rules can silently corrupt the pattern before re ever sees it.
  • re.IGNORECASE and re.MULTILINE are optional flags that change how a pattern behaves.
Why this matters: these three gotchas are responsible for the large majority of "my regex doesn't do what I expected" bugs — greedy matching grabbing too much, a missing r silently changing the pattern, or forgetting a pattern is case-sensitive by default.

Sub-topic 3's Go Deeper box mentioned that quantifiers are greedy by default — here's exactly what that means on text with more than one possible stopping point:

what greedy vs. non-greedy actually try to match
text:        <b>bold</b> and <i>italic</i>
greedy    <.*>   -->  <b>bold</b> and <i>italic</i>   (one huge match)
non-greedy <.*?> -->  <b>   </b>   <i>   </i>          (four small matches)

<.*>'s greedy * tries to match as much text as it possibly can while still finding a closing > somewhere — so it stretches all the way from the very first < to the very last > in the string, swallowing everything in between as one giant match. A ? right after a quantifier makes it non-greedy instead — it matches as little as possible, stopping at the very first > it finds.

What is... greedy vs. non-greedy? A greedy quantifier (*, +, {m,n}) matches the longest possible text that still lets the rest of the pattern succeed. Adding a ? right after it (*?, +?) makes it non-greedy (or "lazy"): it matches the shortest possible text instead.
greedy_vs_nongreedy_demo.py
import re

html_like = "<b>bold</b> and <i>italic</i>"
greedy = re.findall(r"<.*>", html_like)
print(greedy)

non_greedy = re.findall(r"<.*?>", html_like)
print(non_greedy)
actual output of greedy_vs_nongreedy_demo.py
['<b>bold</b> and <i>italic</i>']
['<b>', '</b>', '<i>', '</i>']

This confirms the diagram: the greedy version returns one match spanning the entire string, while the non-greedy version correctly returns each of the four individual tags as its own separate match. Whenever a pattern needs to match "the shortest thing between two delimiters" rather than "everything from the first delimiter to the last one," a non-greedy quantifier is almost always the fix.

The second gotcha has nothing to do with regex syntax at all — it's about how Python reads the pattern string itself before re ever sees it:

What is... a raw string, and why regex needs one? A raw string, written r"...", tells Python not to process backslash escape sequences (like \n for newline) inside it — the backslash is kept exactly as typed. Regex patterns use backslashes constantly (\d, \s, \b...), so without the r prefix, Python's own string rules can quietly turn part of the pattern into something completely different before re ever gets it.
raw_strings_demo.py
import re

text = "cat catalog concatenate"

not_raw_pattern = "\bcat\b"
raw_pattern = r"\bcat\b"

print(repr(not_raw_pattern))
print(repr(raw_pattern))

print(re.findall(not_raw_pattern, text))
print(re.findall(raw_pattern, text))
actual output of raw_strings_demo.py
'\x08cat\x08'
'\\bcat\\b'
[]
['cat']

"\bcat\b" without the r prefix isn't the three characters backslash-b-c-a-t at all — Python's own string rules silently turned \b into the actual backspace control character (\x08) before re ever saw it, which is why repr() shows \x08 instead of a literal backslash-b, and why the search for that corrupted pattern finds nothing. r"\bcat\b" keeps the backslash exactly as typed, so re correctly interprets \b as the word-boundary anchor it's meant to be, matching only the standalone word "cat" — not the "cat" hiding inside "catalog" or "concatenate".

Rule of thumb: write every regex pattern as a raw string, r"...", without exception — even patterns that happen to work without it today can silently break the moment a backslash sequence is added later.

The last gotcha is easy to forget rather than easy to get visibly wrong: patterns are case-sensitive by default, and ^/$ only apply to the whole string by default, not each line within it — two optional flags change both behaviors:

What is... a regex flag? A flag is an optional extra argument passed to a re function (or re.compile()) that changes how the whole pattern behaves. re.IGNORECASE makes matching case-insensitive; re.MULTILINE makes ^/$ match the start/end of each line in a multi-line string, not just the very start/end of the whole string.
flags_demo.py
import re

text = "Python is great. PYTHON is popular. python is fun."
matches_case_sensitive = re.findall(r"python", text)
print(matches_case_sensitive)

matches_ignorecase = re.findall(r"python", text, re.IGNORECASE)
print(matches_ignorecase)

multiline_text = "start of line one\nstart of line two\nend"
starts = re.findall(r"^start", multiline_text, re.MULTILINE)
print(starts)

starts_no_flag = re.findall(r"^start", multiline_text)
print(starts_no_flag)
actual output of flags_demo.py
['python']
['Python', 'PYTHON', 'python']
['start', 'start']
['start']

Without re.IGNORECASE, r"python" only matches the one all-lowercase occurrence — "Python" and "PYTHON" are different text as far as a case-sensitive pattern is concerned. Adding the flag matches all three, regardless of capitalization. Without re.MULTILINE, ^ only anchors to the very beginning of the entire string, finding just one match on the first line; with it, ^ anchors to the start of every line, correctly finding both.

try_it.py
Click "Run Code" — try removing the re.IGNORECASE argument and see how the result changes.
Go Deeper: combining multiple flags

More than one flag can be combined with Python's bitwise OR operator (from Chapter 3): re.IGNORECASE | re.MULTILINE applies both at once. This reads naturally once bitwise | is already familiar — no new operator to learn here, just a new place it shows up.

Quick recap
  • Greedy quantifiers match as much as possible; adding ? after one (*?, +?) makes it non-greedy, matching as little as possible.
  • Always write regex patterns as raw strings (r"...") — without it, Python's own escape-sequence rules can silently corrupt backslash sequences like \d or \b.
  • re.IGNORECASE makes matching case-insensitive; re.MULTILINE makes ^/$ apply per line instead of to the whole string.
In the Real World
  • Form validation (email addresses, phone numbers, postal codes, usernames) is one of the single most common production uses of regex, almost always via re.fullmatch() against user input.
  • Log parsing and monitoring tools use regex constantly to pull structured fields — timestamps, log levels, error codes — out of unstructured text lines, exactly the pattern this chapter's project builds on.
  • Data cleaning pipelines lean on re.sub() to mask sensitive data, normalize inconsistent formatting, and strip unwanted characters before further processing.

Points to Remember

  • A regular expression describes a pattern of text, not one exact string; re.match()/re.search()/re.fullmatch() test a pattern at the start, anywhere, or across the whole string respectively.
  • re.findall() returns every match as a list of strings; re.finditer() returns every match as an iterator of Match objects with position info.
  • Character classes (\d, \w, [...]), quantifiers (*, +, ?, {m,n}), and anchors (^, $) are the core vocabulary a pattern is built from.
  • Parentheses (...) create numbered groups; (?P<name>...) creates named groups — both let a match be broken into labeled, individually retrievable pieces.
  • re.sub() replaces every match of a pattern; re.split() splits text on every match of a pattern — both go beyond what fixed-text string methods can do.
  • re.compile() turns a pattern into a reusable object, worth doing whenever the same pattern gets applied across many lines or calls.
  • Greedy quantifiers match as much as possible (use *?/+? for the opposite); always write patterns as raw strings (r"..."); re.IGNORECASE and re.MULTILINE change matching behavior when needed.