C.W.K.
Stream
Lesson 01 of 10 · published

Python re Module Basics

~10 min · python, re-module

Level 0Pattern-Curious
0 XP0/90 lessons0/15 achievements
0/100 XP to next level100 XP to go0% complete

The four functions you'll use 90% of the time

Python's built-in regex lives in the re module. Four functions cover most use cases:

  • re.search(pattern, text) — find the first match anywhere in text. Returns a Match object or None.
  • re.match(pattern, text) — match at the START of text only. Returns Match or None.
  • re.fullmatch(pattern, text) — match the ENTIRE text. Returns Match or None.
  • re.findall(pattern, text) — return all non-overlapping matches as a list.
  • re.finditer(pattern, text) — return an iterator of Match objects (preferred over findall when you have groups).

The Match object

When a pattern matches, you get a Match object with these key methods:

  • m.group() or m.group(0) — the entire match
  • m.group(N) — the Nth capture group
  • m.group('name') — a named capture group
  • m.groups() — tuple of all numbered groups
  • m.groupdict() — dict of all named groups
  • m.start(), m.end(), m.span() — match position

Match vs search — the most common confusion

re.match only checks the start of the string. re.match(r'world', 'hello world') returns None. Use re.search for "contains." Use re.match for "starts with." Use re.fullmatch for "is exactly."

Code

The Python re basics·python
import re

text = 'order #1138 placed on 2026-05-04'

# search — find anywhere
m = re.search(r'#(\d+)', text)
m.group()      # '#1138'
m.group(1)     # '1138'

# match — only at start
re.match(r'order', text)  # Match
re.match(r'placed', text)  # None

# fullmatch — the whole thing
re.fullmatch(r'\d{4}', '2026')         # Match
re.fullmatch(r'\d{4}', '2026 today')   # None

# findall — list of matches
re.findall(r'\d+', text)
# ['1138', '2026', '05', '04']

# finditer — iterator of Match objects
for m in re.finditer(r'(\w+)=(\d+)', 'a=1 b=2 c=3'):
    print(m.group(1), '→', m.group(2))
# a → 1
# b → 2
# c → 3

External links

Exercise

Take any text file. Write three patterns: one with re.search (find first), one with re.findall (find all), one with re.fullmatch (validate the whole). Notice how each returns different shapes — Match object, list of strings, Match-or-None.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.