Regular Expressions
A regular expression (regex) is a mini-language for describing text patterns, such as "four digits, a dash, two digits". Python's re module uses these patterns to find, check, extract and replace text in a single line.
Your first pattern
Always write patterns as raw strings (r"...") so that backslashes reach the regex engine unchanged.
import re text = "Order 42 shipped on 2026-03-14 to Nakuru" match = re.search(r"\d+", text) # \d+ means "one or more digits" print(match.group()) print(match.start(), match.end()) print(re.findall(r"\d+", text))
re.search() returns a match object for the first match (or None if there isn't one). re.findall() returns a list of every match.
\d+ matches each run of one or more digits. re.search() stops at the first match, "42", which starts at index 6 and ends before index 8; re.findall() collects all four.The building blocks
| Pattern | Matches | Example |
|---|---|---|
. | Any character except a newline | c.t matches cat, cut, c9t |
\d / \D | A digit / a non-digit | \d\d matches 42 |
\w / \W | A word character (letter, digit, underscore) / anything else | \w+ matches Kuza_1 |
\s / \S | Whitespace (space, tab, newline) / non-whitespace | \s+ matches several spaces |
[abc], [a-z] | One character from the set or range | [AEIOU] matches a capital vowel |
[^abc] | One character not in the set | [^0-9] matches a non-digit |
*, +, ? | 0 or more, 1 or more, 0 or 1 of the previous item | colou?r matches color and colour |
{n}, {m,n} | Exactly n, or between m and n repeats | \d{4} matches 2026 |
^, $ | Start and end of the string | ^Hello |
\b | A word boundary | \bcat\b matches cat but not category |
a|b | Either a or b | Mr|Ms|Dr |
( ) | A group: captures part of the match | (\d{4})-(\d{2}) |
To match a special character literally, escape it with a backslash: \. matches a full stop and \+ matches a plus sign.
The main functions
| Function | Does |
|---|---|
re.search(p, s) | Finds the first match anywhere in the string |
re.match(p, s) | Matches only at the start of the string |
re.fullmatch(p, s) | The whole string must match (great for validation) |
re.findall(p, s) | Returns a list of all matches |
re.finditer(p, s) | Returns match objects one at a time |
re.sub(p, repl, s) | Replaces matches |
re.split(p, s) | Splits the string wherever the pattern matches |
Validating input with fullmatch
This pattern accepts Kenyan mobile numbers written as 07..., 01... or +2547.../+2541..., followed by eight more digits.
import re
pattern = r"(?:\+254|0)[17]\d{8}"
numbers = ["0712345678", "+254712345678", "0112345678", "071234567", "0712 345678"]
for number in numbers:
result = "valid" if re.fullmatch(pattern, number) else "invalid"
print(number, "->", result)
(?:...) is a group that doesn't capture; it just lets | choose between \+254 and 0.
Replacing and splitting
import re
print(re.sub(r"\s+", " ", "too many spaces"))
print(re.sub(r"\d{4}$", "XXXX", "0712345678")) # hide the last 4 digits
print(re.split(r"[,;]\s*", "Nairobi, Mombasa;Kisumu, Eldoret"))
Groups: extracting parts of a match
import re
text = "Exam starts 2026-03-14, results 2026-04-30"
m = re.search(r"(\d{4})-(\d{2})-(\d{2})", text)
print(m.group(0)) # the whole match
print(m.group(1)) # first group
print(m.groups())
print(re.findall(r"(\d{4})-(\d{2})-(\d{2})", text))
When a pattern has groups, findall() returns the groups (as tuples when there's more than one) rather than the whole match.
Named groups and compiled patterns
(?P<name>...) gives a group a name, and re.compile() prepares a pattern you'll use many times. Here we pull details out of payment SMS messages:
import re
messages = """Confirmed. KES 1,500.00 sent to JANE WANJIRU on 14/3/26.
Confirmed. KES 250.00 sent to KPLC PREPAID on 15/3/26."""
payment = re.compile(r"KES (?P<amount>[\d,]+\.\d{2}) sent to (?P<name>[A-Z ]+?) on (?P<date>[\d/]+)")
for m in payment.finditer(messages):
amount = float(m["amount"].replace(",", ""))
print(m["date"], m["name"], amount)
Greedy versus lazy, and flags
* and + are greedy: they match as much as possible. Add ? (as in *? or +?) to make them lazy, matching as little as possible.
import re text = 'She said "Nairobi" and "Kampala"' print(re.findall(r'".*"', text)) # greedy print(re.findall(r'".*?"', text)) # lazy print(re.findall(r"python", "Python, PYTHON and python", re.IGNORECASE))
Other useful flags are re.MULTILINE (makes ^ and $ work on each line) and re.DOTALL (lets . match newlines).
Forgetting the r prefix. In a normal string, "\b" is a backspace character, not a word boundary, so re.findall("\bcat\b", text) silently finds nothing. Always write r"\bcat\b".
Using re.match() when you meant re.search(). re.match(r"\d+", "Order 42") returns None because the string doesn't start with a digit. Also check for None before calling .group(), otherwise you'll get AttributeError: 'NoneType' object has no attribute 'group'.
Regex is powerful but can become unreadable. For simple jobs, string methods such as startswith(), split() and replace() are clearer. Real email addresses are notoriously hard to validate fully with a regex; for sign-up forms, a simple check plus a confirmation email is the usual approach.
Key points
- Write patterns as raw strings:
r"\d{4}". searchfinds the first match,findallfinds all,fullmatchvalidates a whole string.subreplaces andsplitsplits using a pattern.- Groups
( )and named groups(?P<name>...)extract parts of a match. - Quantifiers are greedy; add
?to make them lazy.
Tip: use the ← and → keys to move between pages.
