Module 17 · Lesson 01
Advanced Regular Expressions
Go beyond regex basics: named and non-capturing groups, lazy repetition, finditer and match positions, compiled verbose patterns, flags, backreferences, lookarounds, replacement functions and re.escape.
- About 9 minutes
- Builds on earlier lessons
- 12-question quiz at the end
What you will learn
- Named groups
- Greedy or lazy
- Lookarounds and masks
- Watch finditer collect pairs
Patterns with more power
Advanced regex tools name the pieces they find, stop early, and look around without taking.
Named groups
(?P<year>\d{4})lets you readm["year"]instead of counting groups.Lazy
.*?takes as little as it can, so<.*?>stops at the first>.finditer
Hands out each match with its position:
m.start()andm.end().Lookarounds
(?<=\$)\d+finds numbers after a $ sign, without taking the $.
Regex everywhere
Wherever text has a pattern, regex can pull it apart.
- Log filesPull the time, level and message out of every log line.
- Web linksFind every link in a page of text.
- PrivacyHide all but the last four digits of a card number in a report.
- EditorsFind and replace across many files, reusing parts of each match.
Reading a pattern with named groups
This line finds an email address and names both halves. Tap each part to see its job.
Part 1 of 7
match:A match object, or None when nothing fits.
Sharper patterns
Pick an example, change it, then press Run. Say what you expect to see before you press.
Example 1 of 6Named groups
Each group has a name, so the code says what it reads.
Your turn: Add a group for the year alone: (?P<year>\d{4}).
import re line = "2026-11-28 ERROR disk full" m = re.search(r"(?P<date>[\d-]+) (?P<level>[A-Z]+) (?P<msg>.*)", line) print(m["level"]) print(m["msg"]) print(m["date"])
Press Run to see what it prints.Watch finditer collect pairs
Press Step to run one line at a time. Watch the names box change.
Ready. Press Step to run the first line.
- import re
- rx = re.compile(r"(\w+)=(\d+)")
- text = "a=1, b=22, c=x"
- pairs = {}
- for m in rx.finditer(text):
- pairs[m[1]] = int(m[2])
- print(pairs)
- print(len(rx.findall(text)))
Output so far
Nothing printed yet.
What Python does
Python reads the program from the top. Nothing has run yet.
Names
None yet.
Quick guesses
Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.
Question 1 of 6
1.A lazy plus:
import re
print(re.search(r"a+?", "aaa").group())0 of 6 answered
Common regex misconceptions
Each card is something learners often believe. Tap it to see what Python really does.
Misconception 1 of 4
Notes
Everything above, in words. Open it when you want the full explanation.
Read the notesNotesOpenClose
Syntax
The general shape of the statements in this lesson.
(?P<name>...) m.group("name") m.groupdict() named group
(?:...) group without capturing
*? +? ?? {m,n}? lazy repetition
re.finditer(p, s) match objects: .group() .start() .end() .span()
rx = re.compile(p, re.VERBOSE) whitespace and # comments ignored
re.I re.M re.S ignore case, ^ $ per line, . matches newline
\1 (?P=name) backreference to an earlier group
X(?=Y) X(?!Y) lookahead, negative lookahead
(?<=Y)X (?<!Y)X lookbehind, negative lookbehind
re.sub(p, func, s) func(match) returns the replacement
re.sub(p, r"\g<name>", s) named group in a replacement
re.escape(text) match text literallyPress Run to see what it prints.Worked examples
Read the problem, run the code, then read why it works.
Example 1 of 2
Parsing access-log lines with a verbose pattern
Each log line holds a time, a level, a user in square brackets and a message. Write a compiled, commented pattern with named groups, turn matching lines into dictionaries with finditer, and count lines per level.
import re
from collections import Counter
LINE = re.compile(r"""
^(?P<time>\d{2}:\d{2}:\d{2})\s+ # 24-hour time
(?P<level>INFO|WARN|ERROR)\s+ # level
\[(?P<user>[\w.-]+)\]\s+ # user in brackets
(?P<message>.+)$ # the rest of the line
""", re.VERBOSE | re.MULTILINE)
log = """09:14:02 INFO [ana] signed in
09:15:40 WARN [ben.k] password nearly expired
garbage line without a level
09:16:05 ERROR [ana] payment failed: card declined
09:20:11 INFO [cai-2] signed out"""
records = [m.groupdict() for m in LINE.finditer(log)]
for r in records:
print(f"{r['time']} {r['level']:<5} {r['user']:<6} {r['message']}")
print(Counter(r["level"] for r in records))Press Run to see what it prints.Predict first
How it works(open after your guess)
Common pitfalls
Mistakes people make with this topic, and what to write instead.
Pitfall 1 of 3
Greedy repetition swallowing too much
Spot the bug
Can you see what is wrong? Run it to watch it go wrong, then open the fix.
import re print(re.findall(r'"(.*)"', 'say "hi" and "bye"'))
Press Run to see what it prints.Show what goes wrong and the fixWhat goes wrong and the fix
In the real world
Where this shows up in software people use every day.
- Customer support
Cleaning a customer-support export
A support team exports tickets to share with a data analyst. Before sharing, dates written as day/month/year must become ISO dates, accidental repeated words from a buggy form must be removed, and card numbers must be hidden except their last four digits.
Why Python fits
Each rule is one compiled, named pattern, applied in turn. Order matters: card numbers are masked first, and the repeat pattern only looks at letters, so a card's repeated 1111 blocks are never mistaken for a repeated word. The date replacement is a function that reorders the named groups. The repeat pattern uses the backreference
\1with IGNORECASE so "Please please" is caught too, and keeps the first word. The card pattern groups the first three blocks without capturing and keeps only the named last block.Pythonimport re tickets = """Opened 03/11/2025: the the app crashes when I pay. Card 4111 1111 1111 1234 was charged twice on 04/11/2025. Please please call me back.""" def iso_date(m): return f"{m.group('y')}-{m.group('m')}-{m.group('d')}" DATE = re.compile(r"\b(?P<d>\d{2})/(?P<m>\d{2})/(?P<y>\d{4})\b") REPEAT = re.compile(r"\b([a-z]+)\s+\1\b", re.IGNORECASE) CARD = re.compile(r"\b(?:\d{4}[ -]?){3}(?P<last>\d{4})\b") clean = CARD.sub(r"**** \g<last>", tickets) clean = DATE.sub(iso_date, clean) clean = REPEAT.sub(r"\1", clean) print(clean) print("dates fixed:", len(DATE.findall(tickets)))OutputPress Run to see what it prints.
Key takeaways
Tick each one you could explain to a friend.
0 of 5
Common questions
Guess the answer first, then open it.
Is compiling a pattern faster?
Why does findall return tuples sometimes?
Can a lookbehind contain repetition?
Should I parse HTML with regular expressions?
Your notes
Sign in to keep private notes alongside this lesson.
Where to go next
The quiz and the Lab live on their own pages, so this lesson stays about learning.
Finished this lesson?
Create an ID or sign in to save your progress across devices.
Check what you learned
12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.
Keep going in the Lab
7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.
Spaced review
Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.
This lesson at a glance
The 12 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.
What else you can search for and explore
Curious to go further? Each card opens a web search in a new tab.
References
Look things up here whenever you need the exact details.