Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Python
  • Python for AI: The Five Tools You Actually Need
  • Thinking Like a Python Architect in an AI-First World
  • Your First Python Program: print, Comments, sep and end
  • Set Up PyCharm for Python: Install, First Project and First Run
  • Run a Python File and Read the Error: Tracebacks in Three Steps
  • Python Data Types, Variables and Strings: Indexing, Slicing and f-strings
  • Python Operators: Arithmetic, Comparison, Logical, Membership, Identity and Precedence
  • Python Conditionals and Loops: if/elif/else, for, while, break and continue
  • Looping Over Real Data in Python: Dicts, Lists of Dicts, enumerate and zip
  • Checking AI-Written Python Code: A Six-Step Habit That Finds Three Hidden Faults
  • Python Basics Practice: Report Card, Shopping Cart and Password Checker from a Prompt
  • Python Functions: Parameters, Return, Scope (LEGB), *args and **kwargs
  • Type Hints on Python Functions: Parameters, Returns, None and Collections
  • Python lambda, map, filter, Modules and Packages (with pip and venv)
  • Python Functions Practice: Bonus Calculator, Product Pipeline and a Math Package
  • Python Lists, Tuples, Sets and Dicts, Plus Type Hints on Variables
  • Python Comprehensions: List, Dict, Set and Generator Expressions, Read as Loops
  • Python Class Methods, Static Methods and Properties: What Each One Receives
  • Python Classes and Objects: __init__, self and PEP 8 Names
  • Python Inheritance and Polymorphism: super(), Overriding and Duck Typing
  • Python Multiple Inheritance, the MRO and Mixins
  • Python Encapsulation and Special Methods: Underscores, __str__, __add__ and __len__
  • Python Composition, Abstract Classes and Dataclasses
  • Python OOP Practice: Design a Bank, an Employee System and a Library
  • Set Up a Python AI Project with uv, VS Code and an API Key in .env
  • uv and pyproject.toml: Start, Add, Run and Rebuild a Python Project
  • Python try and except Basics: Catch an Error and Keep Going
  • Read and Write a File in Python: open, with, Modes and Encoding
  • Python Custom Exceptions and Advanced Error Handling: raise, raise from and the Call Stack
  • Python Logging and Debugging: Levels, Handlers, logger.exception and breakpoint()
  • Python File Modes, pathlib and Context Managers: x, r+, rb, Path and __enter__/__exit__
  • Python CSV, JSON and Large Files: csv, json, yield Pipelines, tomllib and pickle
  • Python Practice: Build a Log File Analyzer and a File Organizer
  • Python Project Structure for AI-Assisted Development: Packages, config.py and AGENTS.md
  • Regular Expressions in Python: search, findall, Groups and Greedy vs Lazy
  • Testing Python Code with pytest: assert, parametrize, fixtures and pytest.raises
  • Async Python: async def, await, asyncio.gather and the Blocking Trap
  • Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
  • One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
  • Getting Started with Flask: Routes, Jinja2 Templates and WSGI in One Small App
  • Your First Flask App with uv: From an Empty Folder to a Page in Debug Mode
  • Flask Routes, Templates and url_for: Converters, Forms, Redirects and the Signed Session
  • Flask-SQLAlchemy Models and Flask-Migrate: From a Python Class to a Real Table
  • Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review
  • Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
  • Inside a Flask Blog: The App Factory, Blueprints, the Instance Folder and CORS Done Right
  • How a Request and a Login Flow Through a Flask Blog: Flask-Login, CSRF and the Signed Session
  • Testing a Flask Blog with pytest: A Test App from the Factory, Fixtures and the Test Client
  1. Blog
  2. /
  3. Python
  4. /
  5. Advanced Python

Regular Expressions in Python: search, findall, Groups and Greedy vs Lazy

A regex is a stencil for a shape of text. Watch it slide and back up, build patterns with \d, \w, quantifiers and anchors, use search, findall, sub and split, pull parts out with named groups, and test AI-written patterns on edge cases.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Advanced Python

What you will learn

  • Explain how a regex pattern slides over text and why search returns the first match
  • Build patterns from character classes, quantifiers and anchors, written as raw strings
  • Choose between search, match, fullmatch, findall, finditer, sub and split
  • Pull out parts with numbered and named groups, and control greedy vs lazy matching

Before you start

  • Python strings and string methods
  • Lists, dictionaries and loops

You can already search a string with plain methods, but those need the exact words. A regular expression, or regex, searches for a shape instead.

Think about looking for a phone number on a long page. If you know the number, you search for those exact digits. If you don't, you look for a shape: three digits, a dash, four digits. Picture a stencil with that shape cut out, sliding along the line until it fits. It fits 555-0142, and any other number with that shape. A regular expression is that stencil, written as a short string. For one fixed word, plain in is enough.

Your first search

import re

text = "Order #12345 placed at 09:45:30"

match = re.search(r"\d+", text)

print(match)
print(match.group())
print(match.start(), match.end())
print(match.span())
<re.Match object; span=(7, 12), match='12345'>
12345
7 12
(7, 12)

\d means a digit and + means one or more. re.search gives you a match object. group() is the text, and end() is one past the last digit, just like a slice. A match tells you what it found, and where.

How the pattern slides

import re

text = "Order #12345 placed"
pattern = re.compile(r"\d+")

for i in range(len(text)):
    m = pattern.match(text, i)
    print(i, repr(text[i]), m.group() if m else "no")
    if m:
        break
0 'O' no
1 'r' no
2 'd' no
3 'e' no
4 'r' no
5 ' ' no
6 '#' no
7 '1' 12345

This loop acts out what the engine does. At each position from the left it tries the pattern. At position 7 there's a 1, and + keeps taking digits until the space. The engine takes the first position that works, which is why search gives you the first match.

Building blocks: character classes

import re

text = "Room 42, floor 3: call 555-0142"

print(re.findall(r"\d", text))
print(re.findall(r"\w+", text))
print(len(re.findall(r"\s", text)))
print(re.findall(r"[aeiou]", text))
print(re.findall(r"[^a-z\s]", text))
print(re.findall(r"R..m", text))
['4', '2', '3', '5', '5', '5', '0', '1', '4', '2']
['Room', '42', 'floor', '3', 'call', '555', '0142']
5
['o', 'o', 'o', 'o', 'a']
['R', '4', '2', ',', '3', ':', '5', '5', '5', '-', '0', '1', '4', '2']
['Room']
PatternMatches one
\ddigit
\wword character: letter, digit or underscore
\swhitespace
[aeiou]any one of these
[^a-z\s]anything except these
.any character except a new line
\D, \W, \Sthe opposite of the small ones

findall collects every match into a list.

Quantifiers: how many

import re

text = "color colour colouur 5 55 555 5555"

print(re.findall(r"colou?r", text))
print(re.findall(r"colou+r", text))
print(re.findall(r"colou*r", text))
print(re.findall(r"\d{3}", text))
print(re.findall(r"\d{2,3}", text))
['color', 'colour']
['colour', 'colouur']
['color', 'colour', 'colouur']
['555', '555']
['55', '555', '555']

A quantifier applies to whatever is right before it. ? is zero or one, + one or more, * zero or more, {3} exactly three, {2,3} two to three, taking as many as it can. Notice \d{3} finds a second 555 inside 5555. It doesn't care where a number ends.

Anchors: positions, not characters

import re

line = "cat and concatenate"

print(re.findall(r"cat", line))
print(re.findall(r"\bcat\b", line))
print(re.findall(r"^cat", line))
print(re.findall(r"ate$", line))
print(re.findall(r"^cat$", "cat"))
['cat', 'cat']
['cat']
['cat']
['ate']
['cat']

Plain cat also finds the one inside "concatenate". \b is a word boundary, so \bcat\b only matches the whole word. ^ is the start of the text and $ the end. Use both and the whole string has to be exactly "cat", which is handy for checking input.

Always use a raw string

import re

print(len("\n"), len(r"\n"))
print(repr("\bcat"), repr(r"\bcat"))

text = "the cat sat"
print(re.findall("\bcat", text))
print(re.findall(r"\bcat", text))
1 2
'\x08cat' '\\bcat'
[]
['cat']

Python reads the string before re ever sees it. Without the r, \b turns into a backspace character, so the pattern finds nothing, and there's no error to warn you. Always put an r in front of a pattern.

search, match and fullmatch

import re

s = "Call 555-0142 or 555-0199 today"

print(re.match(r"\d+", s))
print(re.search(r"\d{3}-\d{4}", s).group())
print(re.fullmatch(r"\d{3}-\d{4}", "555-0142"))
print(re.fullmatch(r"\d{3}-\d{4}", s))
None
555-0142
<re.Match object; span=(0, 8), match='555-0142'>
None

search finds something anywhere, match only tries at the start, and fullmatch needs the pattern to cover the whole string.

The most common regex error

import re

m = re.search(r"\d+", "no digits here")

print(m)
print(m.group())
None
Traceback (most recent call last):
  File "S04L05_Regex\no_match_error.py", line 6, in <module>
    print(m.group())
          ^^^^^^^
AttributeError: 'NoneType' object has no attribute 'group'

Nothing matched, and you asked for the text anyway. Whenever a search can miss, check first: if m: print(m.group()), else print "no match".

findall and finditer

import re

s = "Call 555-0142 or 555-0199 today"
pat = r"\d{3}-\d{4}"

print(re.findall(pat, s))

for m in re.finditer(pat, s):
    print(m.group(), m.span())
['555-0142', '555-0199']
555-0142 (5, 13)
555-0199 (17, 25)

If you only need the text, use findall. If you need positions or groups too, use finditer.

Groups: pull out the parts

import re

text = "Paid at 09:45:30"
m = re.search(r"(\d{2}):(\d{2}):(\d{2})", text)

print(m.group(0))
print(m.group(1))
print(m.group(2))
print(m.groups())

times = "Start 09:15, end 17:40"
print(re.findall(r"(\d{2}):(\d{2})", times))
09:45:30
09
45
('09', '45', '30')
[('09', '15'), ('17', '40')]

Round brackets make a group. group(0) is always the whole match. When a pattern has groups, findall gives back the groups, not the whole match.

Named groups

import re

pat = r"(?P<hour>\d{2}):(?P<minute>\d{2})"
m = re.search(pat, "Paid at 09:45")

print(m.group("hour"))
print(m["minute"])
print(m.groupdict())

for m in re.finditer(pat, "Start 09:15, end 17:40"):
    print(m["hour"], "->", m["minute"])
09
45
{'hour': '09', 'minute': '45'}
09 -> 15
17 -> 40

(?P<name>...) gives a group a name. When you come back to the pattern later, the names tell you what each part means.

Or, with a non-capturing group

re.findall(r"cat|dog", "I have a cat and two dogs") gives ['cat', 'dog']: the pipe means or, and the "s" isn't part of the pattern. r"(?:cat|dog)s?" gives ['cat', 'dogs']. (?:...) groups without capturing, so findall still returns the whole match.

Changing text: sub and split

import re

s = "Call 555-0142 or 555-0199 today"

print(re.sub(r"\d{3}-\d{4}", "XXX-XXXX", s))
print(re.sub(r"\d{3}-(\d{4})", r"XXX-\1", s))
print(re.split(r"[,;\s]+", "a, b; c  d"))
print(re.split(r",", "a,b,c", maxsplit=1))
Call XXX-XXXX or XXX-XXXX today
Call XXX-0142 or XXX-0199 today
['a', 'b', 'c', 'd']
['a', 'b,c']

\1 in the replacement brings group 1 back, so you hide the start and keep the end. split cuts wherever the pattern matches, in any mix of separators.

compile a pattern you reuse

import re

phone = re.compile(r"\d{3}-\d{4}")
s = "Call 555-0142 or 555-0199 today"

print(phone.search(s).group())
print(phone.findall(s))
print(phone.sub("XXX-XXXX", s))

hello = re.compile(r"hello", re.IGNORECASE)
print(hello.findall("Hello, HELLO, hello"))
555-0142
['555-0142', '555-0199']
Call XXX-XXXX or XXX-XXXX today
['Hello', 'HELLO', 'hello']

The gain is a clear name and one place to change the pattern. re.IGNORECASE means capitals don't matter.

Greedy, backing up, and lazy

import re

html = "<b>bold</b> end"
rest = html[1:]

for n in range(len(rest), 0, -1):
    nxt = rest[n:n + 1]
    ok = nxt == ">"
    print(f".+ takes {n:2}, next {nxt!r:5}", ok)
    if ok:
        break

print(re.search(r"<.+>", html).group())
.+ takes 14, next ''    False
.+ takes 13, next 'd'   False
.+ takes 12, next 'n'   False
.+ takes 11, next 'e'   False
.+ takes 10, next ' '   False
.+ takes  9, next '>'   True
<b>bold</b>
Greedy versus lazy on the text b tag bold close b tag and i tag italic close i tag: greedy .+ runs to the last greater-than sign and gives one long match; lazy .+? stops at the first greater-than sign, giving four separate tags text <b>bold</b> and <i>italic</i> <.+> one match: takes the most, backs up to the last > <.+?> <b> </b> <i> </i> four matches
Greedy takes the most and backs up. Lazy takes the least and grows.

+ is greedy: .+ takes everything it can, all 14 characters. Then the pattern needs a > and there's nothing left, so it gives one character back, and another, until the next character is >. It went straight past the first >. Add a ? after the + to make it lazy:

import re

html = "<b>bold</b> and <i>italic</i>"

print(re.findall(r"<.+>", html))
print(re.findall(r"<.+?>", html))
print(re.findall(r"<[^>]+>(.+?)</[^>]+>", html))
['<b>bold</b> and <i>italic</i>']
['<b>', '</b>', '<i>', '</i>']
['bold', 'italic']

The last pattern puts the lazy text in a group, so findall gives just the words.

Test AI-written patterns on edge cases

AI tools write a regex in seconds, and you should use them for it. But a pattern that works on one example can still be wrong.

import re

loose = r"\w+@\w+\.com"
better = r"[\w.+-]+@[\w-]+(\.[\w-]+)+"
tests = [
    "[email protected]",
    "[email protected]",
    "[email protected]",
    "ana@@example.com",
    "ana@example",
    "[email protected]",
]

for t in tests:
    a = re.fullmatch(loose, t) is not None
    b = re.fullmatch(better, t) is not None
    print(f"{t:24} loose={a!s:5} better={b}")
ana@example.com          loose=True  better=True
ana.k@mail.example.com   loose=False better=True
ana@example.org          loose=False better=True
ana@@example.com         loose=False better=False
ana@example              loose=False better=False
a+news@ex-ample.co.uk    loose=False better=True

The loose pattern passes the first address, so it looks fine, but it fails three good ones. \. means an actual dot. Make a list of good inputs that must pass and bad ones that must fail, and run it every time the pattern changes.

Try it yourself

In the note "Paid 250 at 09:45, due at 14:30", write a pattern with two named groups for the hour and minute and print each groupdict(). One solution prints:

{'hour': '09', 'minute': '45'}
{'hour': '14', 'minute': '30'}

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Python · 35 of 48

Previous
Python Project Structure for AI-Assisted Development: Packages, config.py and AGENTS.md
Next post
Testing Python Code with pytest: assert, parametrize, fixtures and pytest.raises

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Related posts

Testing Python Code with pytest: assert, parametrize, fixtures and pytest.raises

A test is a line on a checklist your code must pass every time. Catch a discount bug with assert, read the E lines in the pytest report, cover cases with parametrize, share a cart with a fixture, test errors with pytest.raises, and see why a passing test from an AI tool can prove nothing.

Async Python: async def, await, asyncio.gather and the Blocking Trap

One cook, several pots: async lets one program wait on many things at once. See what async def and await really do, why three awaits in a row are no faster, how gather and TaskGroup bring 0.6 seconds down to 0.2, and the two mistakes that catch almost everyone.

Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose

One small project lists two blog posts three times: as a Django view, a Flask route and a FastAPI endpoint. See each shape with its real output, what each framework includes, and a three-question way to choose.

One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask

The same blog built in Django, FastAPI and Flask, compared line by line: the list route, the Post model, the template loop, the project layout and the extras, with a ROSETTA map you can use to port a feature with AI.

On this page

  • Your first search
  • How the pattern slides
  • Building blocks: character classes
  • Quantifiers: how many
  • Anchors: positions, not characters
  • Always use a raw string
  • search, match and fullmatch
  • The most common regex error
  • findall and finditer
  • Groups: pull out the parts
  • Named groups
  • Or, with a non-capturing group
  • Changing text: sub and split
  • compile a pattern you reuse
  • Greedy, backing up, and lazy
  • Test AI-written patterns on edge cases
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.