Skip to contentSkip to navigation

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 read m["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() and m.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

Tap any part of the code below, or press Next.1 of 7 explored

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}).

Python
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"])
Output
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.

  1. import re
  2. rx = re.compile(r"(\w+)=(\d+)")
  3. text = "a=1, b=22, c=x"
  4. pairs = {}
  5. for m in rx.finditer(text):
  6. pairs[m[1]] = int(m[2])
  7. print(pairs)
  8. 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 notesOpen

Named groups

Numbered groups get hard to follow once a pattern has several. A named group, written (?P<name>...), captures the same way but lets you read the result by name:

Try it 1: edit me, then Run
import re

m = re.search(r"(?P<user>\w+)@(?P<domain>[\w.]+)", "Contact: ana@shop.io")
print(m.group("user"))     # ana
print(m.groupdict())       # {'user': 'ana', 'domain': 'shop.io'}
Output
Press Run to see what it prints.

groupdict() returns every named group at once, ready to become a record. In a replacement you refer to a named group as \g<name>.

Grouping without capturing

Brackets do two jobs: they capture, and they group things for | or repetition. When you only need the grouping, write (?:...). It keeps findall results and group numbers clean:

Try it 2: edit me, then Run
print(re.findall(r"(?:ab)+", "ababx abx"))           # ['abab', 'ab']
print(re.findall(r"\d+(?:\.\d+)?", "3 and 4.25"))    # ['3', '4.25']
Output
Press Run to see what it prints.

With plain brackets, findall would return only the captured parts instead of the whole matches.

Greedy and lazy repetition

*, +, ? and {m,n} are greedy: they take as much text as they can while the rest of the pattern still matches. Adding ? after them makes them lazy: they take as little as possible.

Try it 3: edit me, then Run
html = "<b>bold</b> and <b>more</b>"
print(re.findall(r"<b>(.*)</b>", html))    # ['bold</b> and <b>more']
print(re.findall(r"<b>(.*?)</b>", html))   # ['bold', 'more']
Output
Press Run to see what it prints.

The greedy .* ran to the last </b>. The lazy .*? stops at the first one that lets the pattern finish. An alternative is a negated class, such as <b>([^<]*)</b>, which cannot cross a < at all and is often faster.

finditer and positions

findall gives strings. re.finditer gives one match object per match, lazily, so you can use groups and positions:

Try it 4: edit me, then Run
for m in re.finditer(r"\d+", "a1 bb22 ccc333"):
    print(m.group(), m.start(), m.end(), m.span())
Output
Press Run to see what it prints.

start() and end() are indexes into the text, useful for highlighting matches or reporting where an error is.

Compiling and VERBOSE patterns

re.compile(pattern, flags) turns a pattern into a reusable object with the same methods: .search, .fullmatch, .findall, .finditer, .sub. It also gives the pattern a name in your code. Combined with the VERBOSE flag, a long pattern can be spread over lines with comments, because whitespace and # comments in the pattern are ignored:

Try it 5: edit me, then Run
DATE = re.compile(r"""
    (?P<day>\d{2})   /    # day
    (?P<month>\d{2}) /    # month
    (?P<year>\d{4})       # year
""", re.VERBOSE)

print(DATE.search("due 03/11/2025").groupdict())
Output
Press Run to see what it prints.

In verbose mode, a real space must be written as \ or [ ], or matched with \s.

More flags

Flags combine with |:

  • re.IGNORECASE (re.I): letters match either case.
  • re.MULTILINE (re.M): ^ and $ match at the start and end of each line, not only the whole text.
  • re.DOTALL (re.S): . also matches a newline.
Try it 6: edit me, then Run
log = "ERROR disk\ninfo ok\nerror net"
print(re.findall(r"^error \w+", log, re.I | re.M))   # ['ERROR disk', 'error net']
Output
Press Run to see what it prints.

Backreferences

Inside a pattern, \1 (or (?P=name) for a named group) means "the same text that group 1 matched". That finds repeated words:

Try it 7: edit me, then Run
print(re.findall(r"\b(\w+) \1\b", "this is is a test test"))   # ['is', 'test']
Output
Press Run to see what it prints.

Lookarounds

A lookaround checks what comes before or after a position without including it in the match:

Pattern Meaning
X(?=Y) X, only if followed by Y
X(?!Y) X, only if not followed by Y
(?<=Y)X X, only if preceded by Y
(?<!Y)X X, only if not preceded by Y
Try it 8: edit me, then Run
print(re.findall(r"\d+(?=kg)", "5kg, 7lb, 12kg"))      # ['5', '12']
print(re.findall(r"(?<=\$)\d+", "cost $40, tax 8"))    # ['40']
Output
Press Run to see what it prints.

Lookaheads at the start of a pattern can check several conditions at once: ^(?=.*\d)(?=.*[A-Z]).{8,}$ means "at least 8 characters, containing a digit and a capital letter".

Replacement functions

The replacement in re.sub can be a function. It receives each match object and returns the replacement text, so replacements can be computed:

Try it 9: edit me, then Run
def double(m):
    return str(int(m.group()) * 2)

print(re.sub(r"\d+", double, "3 apples, 10 pears"))   # 6 apples, 20 pears
Output
Press Run to see what it prints.

Escaping user text

When part of a pattern comes from a user or a variable, characters like ., + or ( would be treated as regex syntax. re.escape(text) adds backslashes so the text matches literally: re.search(re.escape("1+1"), "is 1+1 two?").

Knowing when to stop

Regular expressions describe flat patterns well. They are the wrong tool for nested structures such as HTML, JSON or arithmetic with brackets; use a parser (html.parser, json) for those. Keep patterns short or verbose and commented, test them on bad input as well as good, and beware of nested repetition such as (a+)+, which can take exponentially long on some non-matching text.

Syntax

The general shape of the statements in this lesson.

syntax.py
(?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 literally
Output
Press 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

Intermediate

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.

Python
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))
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

VERBOSE lets each part of the pattern sit on its own line with a comment, and MULTILINE makes ^ and $ match at every line, so finditer can scan the whole log at once. The garbage line simply never matches. groupdict() turns each match into a record with readable keys.

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.

Buggy code: run it
import re
print(re.findall(r'"(.*)"', 'say "hi" and "bye"'))
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

Prints ['hi" and "bye']: one match from the first quote to the last

Write this instead

import re
print(re.findall(r'"(.*?)"', 'say "hi" and "bye"'))

Why it happens

.* is greedy and runs to the last quote that still lets the pattern match.

In the real world

Where this shows up in software people use every day.

  1. Cleaning a customer-support export

    Customer support

    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 \1 with 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.

    Python
    import 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)))
    Output
    Press 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?

Python caches recently used patterns, so the speed difference is usually small. The main benefits of re.compile are readability, a name for the pattern, and a natural place for flags and VERBOSE comments.

Why does findall return tuples sometimes?

When a pattern has capturing groups, findall returns the groups instead of the whole match: one string for one group, tuples for several. Use (?:...) for groups you do not need, or finditer for full match objects.

Can a lookbehind contain repetition?

In Python's re module, a lookbehind must match a fixed length, so (?<=\$) works but (?<=\$+) does not. Restructure the pattern, or capture the prefix and use a group instead.

Should I parse HTML with regular expressions?

Only for tiny, controlled snippets. Real HTML is nested and irregular; use html.parser from the standard library or a dedicated library instead.

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

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.

Create ID to save
Lessons done in this module0/3 complete
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

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.