Regular expressions · 4 / 15 Theory

Replacing and splitting with re.sub and re.split

Regular expressions do not only search: they also transform texts.

re.sub: replace

re.sub(pattern, replacement, text) changes all the matches into the replacement:

import re

print(re.sub(r"\d", "*", "PIN 1234"))       # PIN ****
print(re.sub(r"\s+", " ", "a   b    c"))   # a b c

The second example is very useful: it turns any run of spaces into a single one. With count you limit how many replacements are made:

import re

print(re.sub(r"\d", "*", "1234", count=2))   # **34

Reusing groups in the replacement

In the replacement you can reuse what was captured with \1, \2… It is handy to reorder parts of the text:

import re

date = "2026-11-13"

print(re.sub(r"(\d{4})-(\d{2})-(\d{2})", r"\3/\2/\1", date))   # 13/11/2026

Replacement with a function

Instead of a fixed text, you can pass a function. It receives the Match object and returns the replacement text:

import re

def double(m):
    return str(int(m.group()) * 2)

print(re.sub(r"\d+", double, "3 cats and 12 fish"))   # 6 cats and 24 fish

re.split: split

str.split only accepts a fixed separator. re.split accepts a pattern:

import re

print(re.split(r"[,;\s]+", "a,b;c d"))        # ['a', 'b', 'c', 'd']
print(re.split(r"\d+", "one1two22three"))      # ['one', 'two', 'three']

Watch out at the ends: if the text starts or ends with a separator, empty strings appear:

import re

print(re.split(r",", ",a,b,"))   # ['', 'a', 'b', '']

re.compile: reusing a pattern

If you are going to use the same pattern many times, you can compile it once and call its methods:

import re

pattern = re.compile(r"\d{5}")

print(bool(pattern.fullmatch("28001")))   # True
print(pattern.findall("28001 and 08001")) # ['28001', '08001']

Practice with Hide digits, Split by several separators and Change the date format.