Automate everyday tasks with Python · Lesson 10 of 14

Regular expressions, part 1

Find patterns in text with Python's re module: search, findall, character classes, repetition and groups that pull out the parts you need.

About 16 minutes · code runs in your browser, nothing to install

Sometimes you do not know the exact text you are looking for, only its shape: "a word, then @, then a domain", or "three digits, a dash, four digits". A regular expression (regex) is a small pattern language for describing such shapes, and the re module uses it to search text.

re.search(pattern, text) looks for the first place where the pattern matches. It returns a match object or None when nothing matches, so always check the result before using it. .group() gives the matched text.

Pythoneditable
import re

text = "Order 4521 shipped on Monday"
m = re.search(r"\d+", text)
if m:
    print("found:", m.group())
    print("at position", m.start())

print(re.search(r"\d+", "no numbers here"))
Output
found: 4521
at position 6
None
Tip: Write patterns as raw strings, r"...". Then a backslash stays a backslash, and \d reaches the regex engine instead of being treated as a Python escape.

The basic building blocks

  • \d a digit, \w a letter, digit or underscore, \s a space, tab or new line
  • . any character except a new line
  • [abc] one of these characters, [a-z] a range, [^0-9] anything except these
  • + one or more, * zero or more, ? optional, {3} exactly three, {2,4} two to four
  • ^ start of the text, $ end of the text, \b the edge of a word
  • \. a real dot: put a backslash before special characters to match them literally
Pythoneditable
import re

for code in ["AB-1234", "ab-1234", "AB-12345", "XY-0042"]:
    ok = re.search(r"^[A-Z]{2}-\d{4}$", code)
    print(code, "valid" if ok else "invalid")
Output
AB-1234 valid
ab-1234 invalid
AB-12345 invalid
XY-0042 valid

All matches: findall()

re.findall() returns a list of every match. It is the quickest way to pull all the numbers, words or codes out of a text.

Pythoneditable
import re

text = "Tickets: 3 adults at 12.50, 2 children at 6.00, 1 dog free."
print(re.findall(r"\d+", text))
print(re.findall(r"\d+\.\d{2}", text))
print(re.findall(r"\b[a-z]{4,}\b", text))
Output
['3', '12', '50', '2', '6', '00', '1']
['12.50', '6.00']
['adults', 'children', 'free']

Groups: taking a match apart

Parentheses make a group. The whole match is group(0), the first group group(1), and so on; groups() gives them all as a tuple. With (?P<name>...) a group gets a name you can use instead of a number.

Pythoneditable
import re

line = "2026-03-15 ERROR disk full"
m = re.search(r"(\d{4})-(\d{2})-(\d{2}) (\w+)", line)
print(m.group(0))
print(m.groups())
print("month:", m.group(2), "level:", m.group(4))

m = re.search(r"(?P<user>[\w.]+)@(?P<domain>[\w.]+)", "Contact: anna.k@mail.example")
print(m.group("user"), "|", m.group("domain"))
Output
2026-03-15 ERROR
('2026', '03', '15', 'ERROR')
month: 03 level: ERROR
anna.k | mail.example

When the pattern has groups, findall() returns the groups instead of the whole match: one tuple per match if there are several groups.

Pythoneditable
import re

prices = "tea €3.20, cake €4.50, juice €2.80"
for item, amount in re.findall(r"(\w+) €(\d+\.\d+)", prices):
    print(f"{item:6} {float(amount):5.2f}")
Output
tea     3.20
cake    4.50
juice   2.80

✎ Exercise

Find every order number in text. An order number is ORD- followed by exactly five digits. Print the list of numbers (digits only, without ORD-), then how many there are as <n> orders.

Hint: Put \d{5} in a group so findall returns only the digits. ORD-998 has three digits, so it should not match.

Your codewrite your answer, then Run
import re

text = "Paid: ORD-10234, ORD-10240. Refund ORD-998 (old). Open: ORD-10251."
# your code here

Expected output:

['10234', '10240', '10251']
3 orders
Show a solution
Solutioneditable
import re

text = "Paid: ORD-10234, ORD-10240. Refund ORD-998 (old). Open: ORD-10251."
numbers = re.findall(r"ORD-(\d{5})\b", text)
print(numbers)
print(len(numbers), "orders")
Output
['10234', '10240', '10251']
3 orders

Check yourself

1. What does re.search return when nothing matches?

2. Which pattern matches one or more digits?

3. Why write regex patterns as r"..."?

Spotted a mistake on this page? Tell us