Regular expressions: patterns that find text
🌍 In real life. Your bank sends a text: "Paid Tk 450 at the shop. Balance Tk 12300." You want every amount in it. Searching for "450" finds just that one number. What you really want is "any run of digits", whatever the digits are.
A regular expression (regex, for short) describes the shape of the text you want, not the exact text. Step by step:
import re, Python's regex module- write the pattern as a raw string,
r"...", so every backslash reachesreuntouched - a few codes stand for kinds of character:
\da digit,\wa letter, digit or_,\sa space,.any character - square brackets mean "one of these":
[aeiou]is a vowel,[0-9]is any digit re.findall(pattern, text)gives back a list of every match, from left to right
The idea in one sentence: a regular expression is a pattern that describes the text you're looking for, like \d+ for "one or more digits", and re.findall gives back every piece of text that fits it.
Its words:
- pattern (regex): a description of text, like
\d+ \d: any digit;+: one or more of the thing before it- raw string
r"...": keeps backslashes as they are, sor"\d+"reachesreunchanged re.findall(all matches, as a list) andre.search(the first match, orNone)
import re
sms = "Paid Tk 450 at the shop. Balance Tk 12300."
print(re.findall(r"\d", sms))
print(re.findall(r"\d+", sms))
print(re.findall(r"[aeiou]", "Dhaka"))Watch the scanner. The pattern's pieces sit on top, each with what it means. Below is the text, one tile per character, numbered from 0. The glowing lens slides to each place \d+ fits and stretches over the whole number, and each match flies down into the list that findall gives back.
Just the first one: re.search. findall collects everything. re.search stops at the first match and gives back a Match object: m.group() is the text it matched, and m.span() is where (the start, and one past the end). When nothing fits, search gives back None, so check with if m: before using it.
Why the r? In a normal string, Python treats some backslash pairs specially: "\b" becomes an invisible backspace character, not the regex code for a word edge. A raw string r"\b" keeps the backslash, so always write patterns with r.
import re
for text in ["order 7 arrived", "nothing yet"]:
m = re.search(r"\d+", text)
if m:
print("found", m.group(), "at", m.span())
else:
print("no number in:", text)Mistakes and edge cases.
- Forgetting the r.
"\d+"withoutrmakes Python warnSyntaxWarning: "\d" is an invalid escape sequence; always write patterns as raw strings. - Using a match that wasn't found.
re.searchgivesNonewhen nothing fits, som.group()givesAttributeError: 'NoneType' object has no attribute 'group'. Checkif m:first. - Numbers come back as text. findall gives strings; convert with
int(). - An unclosed bracket in a pattern.
re.compile("(ab")givesre.PatternError: missing ), unterminated subpattern at position 0.
Quiz
What does this print?
import re print(re.findall(r"\d", "a1b22"))What does this print?
import re print(re.findall(r"\d+", "a1b22"))What does
\wmatch?- One letter, digit or underscore
- A whole word
- Any character at all
What does this print?
import re m = re.search(r"cat", "a dog and a cat") print(m.group(), m.span())What does this print?
import re print(re.search(r"\d", "no digits"))There's no number in this text, and the program crashes. Which line needs a check before it?
import re m = re.search(r"\d+", "no numbers here") print(m.group())
Coding tasks
Write
amounts(sms: str) -> list[int]: every whole number in the message, as ints, in order.Write
count_vowels(text: str) -> intwithre.findall: how many vowels (a, e, i, o, u, small or capital) the text has.Write
find_email(text: str) -> str | Nonewithre.search: the first email address in the text (letters, digits,_or., then@, a name, a dot and an ending, likemina.r@example.com), orNoneif there is none.