Lesson 44 / 47
Regular Expressions
Pattern-match and extract text with the re module.
Core functions
re.search finds a pattern anywhere in a string; re.findall returns every match; re.sub replaces matches.
import re
text = "Call 9876543210 or 8123456789"
phones = re.findall(r"\d{10}", text)
print(phones) # ['9876543210', '8123456789']
masked = re.sub(r"\d{10}", "[hidden]", text)
print(masked)Common pattern pieces
\d digit, \w word char, \s whitespace, + one-or-more, * zero-or-more, ? optional. Prefix patterns with r"..." to avoid backslash headaches.