1. Home
  2. Blog
  3. Software Development

Software Development

Python Regex Explained: Patterns, Groups, Lookaheads and Pitfalls, Tested

Regular expressions find, extract and rewrite text using compact patterns. Learn the Python regex functions you will use daily, how groups and lookaheads work, and the traps that make patterns wrong or dangerously slow, with every example run.

11 min read
Python regex explained: patterns, groups, lookaheads and pitfalls, tested

Key takeaways

  • Python regex lives in the built-in re module. Always write patterns as raw strings: r"\d+".
  • search finds a match anywhere; match only at the start; fullmatch requires the whole string.
  • Use named groups for readable extraction and lazy quantifiers (+?) to avoid over-matching.
  • Nested quantifiers like (a+)+ can freeze your program. In our test, adding two characters made one check about four times slower.

You have a log file and need every order number, every email address and every date in it. Splitting strings by hand quickly becomes a mess. Python regex, short for regular expressions, describes the shape of the text you want, such as “a hash followed by digits”, and lets the re module find it for you.

We ran every pattern below with Python 3.13 against this sample text, and the outputs shown are from that run:

text = ("Order #101 by asha@example.com on 2026-11-11 for Rs 1,180.50; "
        "order #102 by ben.k@shop.co.in on 2026-11-12 for Rs 300.")

What is a regular expression?

A regular expression is a small pattern language for text. Ordinary characters match themselves, and special characters describe classes, repetitions and positions. \d means a digit, + means “one or more”, so \d+ matches a run of digits. Regex is supported in nearly every language, editor and database, so the time you spend learning it pays off well beyond Python.

Always use raw strings

Regex uses backslashes heavily, and so do Python strings. In a normal string, "\b" is a backspace character, which we confirmed: Python showed it as '\x08'. In regex, \b means a word boundary. Writing the pattern as a raw string, r"\b", passes the backslash through untouched. Make r"..." a habit for every pattern, and many confusing bugs never happen.

search, match and fullmatch

import re

re.search(r"#(\d+)", text).group(1)            # '101'
re.match(r"#\d+", text)                         # None
bool(re.fullmatch(r"\d{4}-\d{2}-\d{2}", "2026-11-11"))   # True

search scans the whole string and returns the first match. match only checks the beginning, which is why it returned None: our text starts with “Order”, not “#”. fullmatch requires the pattern to cover the entire string, which is what you want for validation, such as checking that a field is a date and nothing else. All three return a match object or None, so check before calling .group().

findall and finditer

re.findall(r"#(\d+)", text)              # ['101', '102']
re.findall(r"\d{4}-\d{2}-\d{2}", text)   # ['2026-11-11', '2026-11-12']
re.findall(r"[\w.+-]+@[\w-]+(?:\.[\w-]+)+", text)
# ['asha@example.com', 'ben.k@shop.co.in']

findall returns all matches as a list. Watch how groups change the result: with one group it returns the group’s text, and with two groups it returns tuples:

re.findall(r"#(\d+) by (\S+)", text)
# [('101', 'asha@example.com'), ('102', 'ben.k@shop.co.in')]

For large texts, re.finditer yields match objects one at a time, which saves memory and gives access to positions and named groups.

Core syntax cheat sheet

Pattern Matches
. Any character except newline
\d, \w, \s Digit, word character, whitespace
\D, \W, \S The opposite of each
[abc], [^abc] One of a set, or anything not in it
*, +, ? 0 or more, 1 or more, 0 or 1
{3}, {2,5} Exactly 3, between 2 and 5
^, $ Start and end of the string (or line with MULTILINE)
\b Word boundary
a|b Either a or b
( ), (?: ) Capturing group, non-capturing group

Groups and named groups

m = re.search(r"(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})", text)
m.groupdict()   # {'year': '2026', 'month': '11', 'day': '11'}
m.group(0)      # '2026-11-11'

Named groups, (?P<name>...), make extraction code self-explanatory: m["year"] reads far better than m.group(1), and adding a group later does not shift the numbers. Group 0 is always the whole match. A non-capturing group, (?:...), groups parts of the pattern for repetition or alternation without adding to the results, which keeps findall output clean.

Greedy vs lazy quantifiers

re.findall(r"<.+>",  "<b>bold</b> and <i>it</i>")
# ['<b>bold</b> and <i>it</i>']

re.findall(r"<.+?>", "<b>bold</b> and <i>it</i>")
# ['<b>', '</b>', '<i>', '</i>']

Quantifiers are greedy by default: .+ grabbed everything from the first < to the very last >. Adding ? makes them lazy, so they stop at the first possible end. Even better, be specific: <[^>]+> says “anything except a closing bracket”, which is both clearer and faster. (For real HTML, use a proper parser; this is just a demonstration.)

sub and split

re.sub(r"(\d{4})-(\d{2})-(\d{2})", r"\3/\2/\1", "2026-11-11")   # '11/11/2026'
re.sub(r"\d+", lambda m: str(int(m.group()) * 2), "3 pens, 4 books")   # '6 pens, 8 books'
re.split(r"\s*[,;]\s*", "pen, book;ink ,  lamp")   # ['pen', 'book', 'ink', 'lamp']

sub replaces matches, and the replacement can refer to groups with \1 or \g<name>. Passing a function instead of a string lets you compute each replacement. split handles messy separators that str.split cannot, such as mixed commas and semicolons with uneven spaces.

Lookaheads and lookbehinds

Lookarounds check what comes before or after a position without including it in the match. A classic use is password rules, where several conditions must all be true:

pw = re.compile(r"^(?=.*[A-Z])(?=.*\d)(?=.*[^\w\s]).{8,}$")

'password'   False
'Passw0rd'   False   # no symbol
'Passw0rd!'  True
'P0!a'       False   # too short

Each (?=...) is a positive lookahead that checks one rule from the start of the string. A lookbehind, (?<=...), checks what came before:

re.findall(r"(?<=Rs )[\d,.]+\d", text)   # ['1,180.50', '300']

This extracted the amounts without the “Rs ” prefix. Negative versions, (?!...) and (?<!...), assert that something does not follow or precede. Python’s lookbehinds must have a fixed width, so patterns like (?<=\d+) are rejected. For complex password policies, separate checks in plain code are often easier to read and to give helpful error messages for.

Flags

Flag Effect Our result
re.I Ignore case Found both “Order” and “order”
re.M ^ and $ match at each line 2 matches with, 1 without
re.S . also matches newline a.b matched “a\nb” only with it
re.X Allow whitespace and comments Readable multi-line patterns
re.A ASCII-only \d, \w, \s See the next section
verbose = re.compile(r"""
    (?P<user>[\w.+-]+)    # user part
    @
    (?P<domain>[\w.-]+)   # domain
""", re.X)
verbose.search("mail asha@example.com now").groupdict()
# {'user': 'asha', 'domain': 'example.com'}

Verbose mode turns a cryptic one-liner into something a teammate can review. Use it for any pattern longer than about twenty characters.

Unicode surprises

bool(re.fullmatch(r"\d", "५"))         # True   (Devanagari digit five)
bool(re.fullmatch(r"\d", "५", re.A))   # False

In Python 3, \d matches any Unicode decimal digit, not just 0 to 9. That is helpful for international text, but if a value will later go into int(), a database or an API that expects ASCII digits, a pattern that “validated” the input may let through characters that break the next step. Use [0-9] or the re.A flag when you mean ASCII digits. We met a related bug in our property-based testing article, where a superscript digit broke a parser.

Tip: Compile patterns you reuse with re.compile() and give them descriptive names, such as ORDER_ID = re.compile(r"#(\d+)"). Python caches recent patterns anyway, so the main benefit is readability and having one tested definition.

Catastrophic backtracking

Some patterns take exponential time on inputs that almost match. We tested a classic example, ^(a+)+$, against strings of a’s ending in “b”:

n=16   0.002s
n=20   0.037s
n=22   0.154s
safe pattern ^a+$, n=22: 0.000004s

Each extra character roughly doubled the time, because the engine tries every way of splitting the a’s between the inner and outer groups before giving up. At that rate, 30 characters would take tens of seconds, and a few more would take minutes. If users control the input, this becomes a denial-of-service risk known as ReDoS. Avoid nested quantifiers over the same characters, prefer specific character classes, limit input length before matching, and test patterns with long near-miss inputs.

Testing your patterns

Regex is code, so test it. Write a small table of strings that should match and strings that should not, including empty strings, very long strings, Unicode and near misses, and run it with pytest parametrised tests. Edge cases are where regex bugs hide: an email pattern that rejects plus signs, a date pattern that accepts month 13, or a phone pattern that misses spaces.

When not to use regex

  • Simple checks: "@" in s, s.startswith("INV-") and s.split(",") are clearer and faster.
  • Structured formats: use real parsers for HTML, XML, JSON, CSV and URLs.
  • Dates: regex can check a shape, but use datetime.strptime to check that a date actually exists.
  • Emails: a simple pattern catches typos; only a confirmation email proves an address works.

Final thoughts

Python regex is a precise tool for messy text. Use raw strings, pick search, match or fullmatch deliberately, name your groups, prefer lazy or specific patterns over greedy ones, and write long patterns in verbose mode. Then test them with tricky inputs, including Unicode and long near-misses, so a pattern never surprises you in production.

Frequently asked questions

What is the difference between re.search and re.match?

re.search finds the first match anywhere in the string. re.match only matches at the beginning. In our test, match returned None because the text did not start with the pattern.

Why should I use raw strings for regex in Python?

Raw strings keep backslashes as typed. In a normal string, “\b” becomes a backspace character instead of the regex word boundary.

What is a non-greedy or lazy match?

Adding ? after a quantifier, as in .+?, makes it match as little as possible. It stopped our tag pattern from swallowing the whole line.

How do named groups work in Python regex?

Write (?P<name>pattern), then read the value with match[“name”] or match.groupdict(). Names make extraction code easier to read and maintain.

Why is my regex so slow?

Nested quantifiers such as (a+)+ can cause catastrophic backtracking, where time grows exponentially on near-matching input. Rewrite the pattern and limit input length.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

Prompt Injection Explained: How AI Apps Get Tricked and How to Defend Them

Prompt injection explained for builders: direct and indirect attacks, why keyword filters fail (our test blocked 1 of 4), and…

Read article →
DevOps

DNS Records Explained: A, AAAA, CNAME, MX, TXT and TTL With Real Lookups

DNS records explained with lookups we ran: how resolution works, A and AAAA, CNAME rules, MX and null MX, TXT…

Read article →
DevOps

Feature Flags Explained: Safe Releases, Gradual Rollouts and Flag Hygiene

Feature flags explained with a rollout simulation we ran: flag types, percentage rollouts with stable hashing, kill switches, allow lists,…

Read article →
Test Automation

Test Data Generation With Python Faker: Realistic, Repeatable and Safe Data

Test data generation with Python Faker, run and measured: seeding for repeatable data, locales, unique values, domain-shaped records, edge cases…

Read article →
Software Testing

Shift-Left Testing Explained: Find Bugs Earlier Without Slowing the Team

Shift-left testing explained: what it means, why early defects are cheaper, practices from requirement reviews to CI checks, the tester's…

Read article →
Databases & SQL

SQL String Functions Explained: TRIM, SUBSTR, REPLACE, CONCAT and Data Cleanup

SQL string functions explained with queries we ran: concatenation and NULL, TRIM, UPPER and LOWER, SUBSTR and INSTR, REPLACE, padding,…

Read article →
Databases & SQL

SQL Triggers Explained: BEFORE and AFTER Triggers, Audit Logs and Pitfalls

SQL triggers explained with triggers we ran: BEFORE vs AFTER, OLD and NEW, audit logs, validation, stock updates, WHEN conditions,…

Read article →
Software Development

Python JSON Module Explained: dumps, loads, Custom Types and Common Errors

The Python JSON module explained with code we ran: dumps and loads, files, type conversions, dates and decimals, custom encoders,…

Read article →
Software Development

ES Modules vs CommonJS: How JavaScript Imports Work in Node.js, Tested

ES modules vs CommonJS explained with code we ran in Node.js: import and export syntax, require, live bindings, caching, top-level…

Read article →
Software Development

Python Regex Explained: Patterns, Groups, Lookaheads and Pitfalls, Tested

Python regex explained with patterns we ran: search vs match, findall, groups and named groups, greedy vs lazy, sub, lookaheads,…

Read article →
Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
DevOps

SSH Keys Explained: How They Work, ssh-keygen, Ed25519 and Safe Habits

SSH keys explained with keys we generated: public vs private keys, ssh-keygen, Ed25519 vs RSA, fingerprints, passphrases, ssh-agent, authorized_keys, config…

Read article →
DevOps

HTTP Caching Explained: Cache-Control, ETag and 304 Responses, With a Live Test

HTTP caching explained with a small server we ran: Cache-Control directives, max-age, no-cache vs no-store, ETag revalidation and 304 responses,…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →
Databases & SQL

SQL Constraints Explained: NOT NULL, UNIQUE, CHECK and FOREIGN KEY, Tested

SQL constraints explained with tests we ran: NOT NULL, UNIQUE, CHECK, DEFAULT, PRIMARY and FOREIGN KEY, the NULL loopholes, SQLite's…

Read article →
Databases & SQL

SQL Date Functions Explained: Adding, Comparing and Grouping Dates Without Bugs

SQL date functions explained with queries we ran: adding intervals, month-end surprises, date differences, the BETWEEN trap, grouping by day,…

Read article →
Software Development

Python asyncio Explained: async, await, gather and TaskGroup With Real Timings

Python asyncio explained with code we timed: coroutines, await, gather, TaskGroup, error handling, timeouts, limiting concurrency and the blocking-call mistake…

Read article →
Software Development

Debounce vs Throttle in JavaScript: How They Work, When to Use Each, Tested

Debounce vs throttle in JavaScript explained with timings we measured in Node.js: how each works, simple implementations, leading and trailing…

Read article →
Software Development

Python Context Managers Explained: The with Statement, contextlib and Real Uses

Python context managers explained with code we ran: how with works, __enter__ and __exit__, contextlib.contextmanager, suppress, ExitStack, database transactions and…

Read article →
Artificial Intelligence

LLM Temperature and Top-p Explained: How AI Models Choose Their Next Word

LLM temperature and top-p explained with a simulation we ran: how probabilities are reshaped, what top-p keeps, recommended settings by…

Read article →
DevOps

YAML Explained: Syntax, the Norway Problem and Other Traps We Tested

YAML explained with a parser test: basic syntax, lists and maps, the Norway problem, versions turning into floats, octal zip…

Read article →
DevOps

Cron Jobs Explained: Syntax, Real Schedules and the Mistakes That Break Them

Cron jobs explained with schedules we verified: the five fields, operators, real examples, the day-of-month OR day-of-week trap, environment problems,…

Read article →
Software Testing

Bug Life Cycle in Software Testing: Every Status, Who Owns It and Common Mistakes

The bug life cycle explained: every defect status from New to Closed, who owns each step, rejected, deferred and reopened…

Read article →
Test Automation

Property-Based Testing in Python: Hypothesis Finds the Bugs Your Examples Miss

Property-based testing explained with Hypothesis tests we ran: properties vs examples, strategies, shrinking, the real bugs it found in our…

Read article →
Databases & SQL

SQL Pagination Explained: OFFSET vs Keyset, With a Million-Row Test

SQL pagination explained with a million-row test we ran: LIMIT and OFFSET, why deep pages get slow, keyset (cursor) pagination,…

Read article →
Databases & SQL

SQL EXISTS vs IN: Differences, the NOT IN NULL Trap and Performance

SQL EXISTS vs IN explained with queries we ran: how each works, why NOT IN returns no rows when a…

Read article →
Artificial Intelligence

LLM Tokens Explained: How AI Models Read Text, Count Costs and Fill Context Windows

LLM tokens explained with a tokenizer we ran: how text is split, why counts differ by language and tokenizer, context…

Read article →
Software Testing

The Test Pyramid Explained: Layers, Ratios and When to Break the Shape

The test pyramid explained: unit, integration and end-to-end layers, sensible ratios, the ice cream cone anti-pattern, the testing trophy and…

Read article →
Test Automation

pytest Fixtures Explained: Scope, yield Teardown, conftest.py and Factories

pytest fixtures explained with a suite we ran: how fixtures work, scopes, yield teardown, conftest.py, factory fixtures, parametrized fixtures, built-ins…

Read article →
Artificial Intelligence

AI Hallucinations Explained: Why Language Models Make Things Up and How to Reduce It

AI hallucinations explained: what they are, why language models produce them, common types, how to reduce them with grounding and…

Read article →
Test Automation

Mocking in Python: unittest.mock, patch and the Mistakes That Make Tests Lie

Mocking in Python with unittest.mock, tested: Mock and return_value, side_effect, patching where a name is used, spec and autospec, mocking…

Read article →
Software Testing

Code Coverage Explained: Line vs Branch Coverage and What 100% Really Means

Code coverage explained with a real coverage.py run: line, branch and condition coverage, reading a report, why 100% coverage can…

Read article →
Artificial Intelligence

What Are AI Agents? How They Work, With a Simple Agent Loop You Can Run

What are AI agents? A plain guide to the agent loop, tools, memory and guardrails, with a small Python loop…

Read article →
Test Automation

TDD vs BDD: Key Differences, One Feature Built Both Ways and When to Use Each

TDD vs BDD explained with one discount feature built both ways: red-green-refactor with code we ran, Given-When-Then scenarios, tools, trade-offs…

Read article →
Software Testing

User Acceptance Testing (UAT): Process, Checklist and Real Examples

User acceptance testing explained: who runs it, how it differs from QA, a seven-step process, a UAT test case template,…

Read article →