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.
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']
| Pattern | Matches one |
|---|---|
\d | digit |
\w | word character: letter, digit or underscore |
\s | whitespace |
[aeiou] | any one of these |
[^a-z\s] | anything except these |
. | any character except a new line |
\D, \W, \S | the 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>
+ 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'}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.
