🎓 A1Learner
🔍

Python Regular Expressions

A regular expression is a pattern. A pattern is a short text recipe that describes what to find.

Finding numbers by hand

This code hunts for numbers with a loop. The loop tracks a number while digits last.

text = "Room 12 has 3 beds and 40 chairs"
numbers = []
current = ""
for ch in text:
    if ch.isdigit():
        current += ch
    elif current:
        numbers.append(current)
        current = ""
if current:
    numbers.append(current)
print(numbers)

Search anywhere

search looks through the whole string.

import re
match = re.search(r"cat", "the cat sat")
print(match.group())

Match at the start

match only checks the start of the string.

import re
match = re.match(r"the", "the cat sat")
print(match.group())

Find all matches

findall returns every match in a list.

import re
print(re.findall(r"\d+", "Room 12 has 3 beds and 40 chairs"))

Character classes

A character class matches one kind of character. \d is a digit. \w is a word character. \s is whitespace.

import re
print(re.findall(r"\d+", "a1 b22 c333"))
print(re.findall(r"\w+", "hi there_2"))
print(len(re.findall(r"\s", "a b c")))

Anchors

An anchor pins a pattern to a place. ^ means the start. $ means the end.

import re
print(bool(re.search(r"^Hello", "Hello world")))
print(bool(re.search(r"world$", "Hello world")))

Read a Match

group() gives the whole match. Numbered groups give parts of it.

import re
match = re.search(r"(\d+)-(\d+)", "pages 12-15")
print(match.group())
print(match.group(1))
print(match.group(2))

Example

import re

text = "In 2019 the tent cost $45. In 2022 the tent cost $60 and the lamp cost $15."
years = re.findall(r"\b\d{4}\b", text)
prices = re.findall(r"\$\d+", text)
print("Years:", years)
print("Prices:", prices)

Key points

  • Pattern: a short recipe that describes text to find
  • Use re.search() to find a pattern anywhere in a string
  • Use re.match() to check a pattern only at the start
  • Use re.findall() to collect every match as a list
  • Use a raw string like r"\d+" so backslashes stay simple

In this example, one paragraph holds all the data. The first findall call looks for four digits as a whole word. That finds the two years. The second call looks for a dollar sign followed by digits. That finds the three prices. Each result is a plain list of strings.

Note

A Match object prints a memory address.

Print its .group() result instead.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

Which function collects every match in a string as a list?