Regex Patterns, Classes and Groups
18 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Text from forms, files and logs is messy. A regular expression, or regex, is a short pattern that describes the text you want. One pattern can replace a loop with many ifs.
A pattern describes text
Regular expression is a pattern written in a small language that describes a set of strings. The re module checks text against it and can find, check or split text.
Python keeps regex in the re module. A pattern is a string, and you write it as a raw string, r"...", so backslashes reach re untouched.
import re
m = re.search(r"\d+", "Order 4521 shipped")print(m.group())Example 1 · Find a number in text
import re
text = "Order 4521 shipped on day 7"m = re.search(r"\d+", text)print(m.group())print(m.start(), m.end())4521 6 10
What this code does
\d+means one or more digits, so the first run of digits wins.start()andend()give the place in the text where the match sits.
re.search scans the text and returns a match object for the first hit, or None.
Classes and quantifiers
Quantifier is the part of a pattern that sets how many times the item before it may repeat. The common ones are ?, *, +, {n} and {n,m}.
A character class matches one character from a set: \d a digit, \w a letter, digit or underscore, \s a space, [A-Z] a capital letter. A quantifier says how many times to repeat the item before it.
import re
print(re.search(r"[A-Z]{2}\d{4}", "Ticket AB1234 open").group())Example 2 · Classes and counts
import re
codes = ["AB1234", "ab1234", "AB123"]for code in codes: print(code, bool(re.search(r"^[A-Z]{2}\d{4}$", code)))AB1234 True ab1234 False AB123 False
What this code does
[A-Z]{2}is two capital letters and\d{4}is four digits.- Lowercase letters and a short number both fail.
Quantifiers: ? zero or one, * zero or more, + one or more, {n} exactly n, {n,m} between n and m.
Anchors and alternation
Anchor is a pattern item that matches a position instead of a character, such as the start of the text (^), the end ($) or the edge of a word (\b).
An anchor matches a position, not a character. ^ is the start of the text, $ the end, and \b the edge of a word. The bar | means "this or that".
import re
print(bool(re.search(r"^(cat|dog)$", "dog")))print(bool(re.search(r"\bcat\b", "concat")))Example 3 · Word edges and choices
import re
words = ["cat", "concat", "the cat sat"]for w in words: print(w, bool(re.search(r"\bcat\b", w)))print(bool(re.search(r"^(red|green)$", "green")))cat True concat False the cat sat True True
What this code does
\bmakescatmatch only as a whole word.- The bar picks
redorgreen, and the anchors make it the whole text.
Without \b, cat would also match inside concat.
Groups pick out the parts
Capturing group is a part of a pattern in round brackets. The text it matches is stored, so you can read it with group(n) or group("name") after the match.
Round brackets make a group. The text each group matched is saved, numbered from 1 by position. Name a group with (?P<name>...) to read it by name.
import re
m = re.search(r"(\d{4})-(\d{2})-(\d{2})", "Due 2026-11-08")print(m.group(1), m.group(2), m.group(3))Example 4 · Numbered and named groups
import re
line = "Due 2026-11-08"m = re.search(r"(\d{4})-(\d{2})-(\d{2})", line)print(m.groups())n = re.search(r"(?P<year>\d{4})-(?P<month>\d{2})", line)print(n.group("year"), n["month"])('2026', '11', '08')
2026 11What this code does
groups()returns every group in order.- A named group is read with
group("year")orn["month"], which is clearer than a number.
group(0) is the whole match. groups() returns all the groups as a tuple.
Next step
Check your understanding
11 quick questions