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.
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.
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"))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.
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"))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.
import re
EMAIL = re.compile(r"""
[\w.+-]+ # the name part
@
[\w-]+ # domain
(?:\.[\w-]+)+ # one or more .something endings
""", re.VERBOSE)
text = "Write to [email protected] or [email protected], 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."))['[email protected]', '[email protected]'] ['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.
import re
EMAIL = re.compile(r"([\w.+-])[\w.+-]*@([\w-]+(?:\.[\w-]+)+)")
text = "Complaint from [email protected], copied to [email protected]."
print(EMAIL.sub(r"\1***@\2", text))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.
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)}")(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.
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"))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.
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
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))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?
\1 and \2 refer to the groups, so the two words swap places.
2. What does the re.IGNORECASE flag do?
With it, todo also matches TODO and Todo.
3. What does \D match?
Upper-case versions mean "not": \D not a digit, \S not a space, \W not a word character.