Regular expressions · 1 / 15 Theory

Finding patterns with re

A regular expression (*regex*) is a pattern that describes a set of texts: "three digits in a row", "a word that starts with A"… In Python they are used with the re module.

import re

text = "I have 3 cats and 12 fish"

result = re.search(r"\d+", text)
print(result.group())  # 3

\d+ means "one or more digits". re.search scans the text and returns the first match.

Raw strings

Patterns are written with r"..." (a *raw* string). That way the backslash reaches re unchanged and you do not have to double it:

print("\d")   # \d  (works, but is fragile)
print(r"\d")  # \d  (always do this)

search, match and fullmatch

There are three functions to check a pattern. The difference is where it must match:

FunctionWhere it matches
re.searchAnywhere in the text
re.matchAt the start of the text
re.fullmatchWith the whole text
import re

print(bool(re.search(r"\d+", "abc123")))     # True
print(bool(re.match(r"\d+", "abc123")))      # False
print(bool(re.fullmatch(r"\d+", "abc123")))   # False
print(bool(re.fullmatch(r"\d+", "123")))      # True

To validate a piece of data (a postal code, a phone number) use fullmatch. To look for something inside a text, use search.

The result: None or a Match object

If there is no match they return None, which counts as false. That is why you write:

import re

result = re.search(r"\d+", "no numbers")

if result:
    print(result.group())
else:
    print("None found")   # None found

If there is a match, the object offers .group() (the text found), .start() and .end() (positions):

import re

r = re.search(r"\d+", "I have 12 fish")
print(r.group(), r.start(), r.end())  # 12 7 9

Practice with First number and Postal code.