Automate everyday tasks with Python · Lesson 11 of 14

Regular expressions, part 2

Replace text with re.sub, compile patterns with flags, and solve real jobs: hide e-mail addresses, tidy phone numbers and convert dates.

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

Finding text is half of the job. The other half is changing it: hiding private data, rewriting dates into one format, turning phone numbers written ten different ways into one. This lesson builds on Regular expressions, part 1.

Replacing with re.sub()

re.sub(pattern, replacement, text) replaces every match. In the replacement, \1, \2 refer back to the groups, so you can reorder parts of a match. Here day/month/year dates become year-month-day.

Pythoneditable
import re

text = "Paid 03/02/2026, due 15/03/2026, late fee from 01/04/2026."
iso = re.sub(r"(\d{2})/(\d{2})/(\d{4})", r"\3-\2-\1", text)
print(iso)

print(re.sub(r"\s+", " ", "too    many     spaces"))
Output
Paid 2026-02-03, due 2026-03-15, late fee from 2026-04-01.
too many spaces

The replacement can also be a function. It receives each match object and returns the text to put in its place, which lets you calculate the replacement.

Pythoneditable
import re

def add_vat(m):
    price = float(m.group(1))
    return f"{price * 1.2:.2f} EUR"

print(re.sub(r"(\d+\.\d{2}) EUR", add_vat, "Lamp 40.00 EUR, cable 2.50 EUR"))
Output
Lamp 48.00 EUR, cable 3.00 EUR

Compiling patterns and flags

re.compile() turns a pattern into an object you can reuse, which keeps long scripts readable. Flags change how matching works: re.IGNORECASE ignores case, and re.VERBOSE lets you spread a pattern over several lines with comments.

Pythoneditable
import re

EMAIL = re.compile(r"""
    [\w.+-]+        # the name part
    @
    [\w-]+          # domain
    (?:\.[\w-]+)+   # one or more .something endings
""", re.VERBOSE)

text = "Write to info@shop.example or Sam.Lee+news@mail.example.org, not to @nobody."
print(EMAIL.findall(text))

TODO = re.compile(r"\btodo\b", re.IGNORECASE)
print(TODO.findall("TODO: fix. Todo later. todos are fine."))
Output
['info@shop.example', 'Sam.Lee+news@mail.example.org']
['TODO', 'Todo']

Real tasks: e-mails and phone numbers

Real e-mail rules are very complicated; a simple pattern like the one above finds addresses in ordinary text but cannot tell whether an address really works. Before sharing a log or a document, you may want to hide personal data. This keeps the first letter and the domain of each address.

Pythoneditable
import re

EMAIL = re.compile(r"([\w.+-])[\w.+-]*@([\w-]+(?:\.[\w-]+)+)")
text = "Complaint from anna.k@mail.example, copied to boss@shop.example."
print(EMAIL.sub(r"\1***@\2", text))
Output
Complaint from a***@mail.example, copied to b***@shop.example.

People write the same number in many ways. Throw away everything that is not a digit with re.sub(r"\D", "", ...) (\D means "not a digit"), then format the digits the way you want.

Pythoneditable
import re

def tidy_phone(text):
    digits = re.sub(r"\D", "", text)
    if len(digits) != 10:
        return f"?? {text}"
    return f"{digits[:3]}-{digits[3:6]}-{digits[6:]}"

for raw in ["(555) 123-4567", "555.123.4567", "555 1234567", "123-45"]:
    print(f"{raw:16} -> {tidy_phone(raw)}")
Output
(555) 123-4567   -> 555-123-4567
555.123.4567     -> 555-123-4567
555 1234567      -> 555-123-4567
123-45           -> ?? 123-45

re.finditer() gives match objects one by one, with positions, which is handy when you need each match and its groups. re.split() splits text wherever the pattern matches.

Pythoneditable
import re

text = "Meeting 2026-03-15, review 2026-04-02, launch 2026-05-20."
for m in re.finditer(r"(\w+) (\d{4})-(\d{2})-(\d{2})", text):
    event, year, month, day = m.groups()
    print(f"{event:8} {day}.{month}.{year}")

print(re.split(r"\s*[,;]\s*", "apples, pears;plums ,  figs"))
Output
Meeting  15.03.2026
review   02.04.2026
launch   20.05.2026
['apples', 'pears', 'plums', 'figs']

✎ Exercise

Rewrite every date in text written as day.month.year (for example 5.3.2026 or 15.03.2026) into the form 2026-03-05, with two-digit month and day. Use re.sub with a function.

Hint: Pattern: (\d{1,2})\.(\d{1,2})\.(\d{4}). In the function, int() the parts and format them with :02d.

Your codewrite your answer, then Run
import re

text = "Arrive 5.3.2026, leave 15.03.2026, pay by 1.4.2026."
# your code here

Expected output:

Arrive 2026-03-05, leave 2026-03-15, pay by 2026-04-01.
Show a solution
Solutioneditable
import re

def to_iso(m):
    day, month, year = m.groups()
    return f"{year}-{int(month):02d}-{int(day):02d}"

text = "Arrive 5.3.2026, leave 15.03.2026, pay by 1.4.2026."
print(re.sub(r"(\d{1,2})\.(\d{1,2})\.(\d{4})", to_iso, text))
Output
Arrive 2026-03-05, leave 2026-03-15, pay by 2026-04-01.

Check yourself

1. In re.sub(r"(\w+) (\w+)", r"\2 \1", "Anna Rossi"), what is the result?

2. What does the re.IGNORECASE flag do?

3. What does \D match?

Spotted a mistake on this page? Tell us