Regular Expressions · 17 min

Find, split, and replace text

Normalize separators and find repeated matches with compiled patterns.

Jump to the automation lab

re.split() divides text wherever a pattern matches. re.sub() replaces matches, and re.findall() returns all non-overlapping matches. If a findall pattern includes capturing groups, those groups change the shape of the returned items.

re.compile() gives a reusable pattern with its own methods. For one exact delimiter, str.split() is simpler. A character class is useful when several separators are allowed in the same field.

Follow the example

The field uses several different delimiters.

Worked examples

Normalize spaces and collect ticket IDs

Substitution makes neighboring whitespace consistent. Word boundaries keep the search from taking an ID out of a longer word.

tickets.py
import re

text = "assigned  AB-042\t then CD-113"
clean = re.sub(r"\s+", " ", text)
print(clean)
print(re.findall(r"\b[A-Z]{2}-[0-9]{3}\b", clean))

Run the example and practice

Support the vertical bar as a third separator. Discard empty fields and preserve the original order.

Target output

oak / elm / ash / pine
Show a hint

Inside a square-bracket character class, | is a literal character.

Output

Ready

Run your code to see the output here.

Check output also tests your code with additional cases.

The first run downloads Python. Code runs in your browser. Progress and drafts are stored on this device.

Show one solution
import re

separators = re.compile(r"[,;|]+")

def tags(text):
    return [part.strip() for part in separators.split(text) if part.strip()]

print(" / ".join(tags(" oak,elm ; ash | pine ")))

Automation lab

Tidy a sample speech transcript

Clean repeated spaces and an automatic speaker label before pasting a line of transcript into meeting notes.

Output

Ready

Run the example to see the output here.

Add a second line with a different speaker number. Explore what changes when you pass re.MULTILINE to the first substitution.