Python ยท Chapter 34 of 45
Regular Expressions
REGEX matches patterns in text. Python's `re` module provides `search`, `match`, `findall`, `sub` and more.
Common patterns: `\d` digit, `\w` word char, `\s` whitespace, `.` any char, `*` zero-or-more, `+` one-or-more.
Groups
Parentheses capture parts of the match. Access with `.group(n)` on a match object.
Substitution
`re.sub(pattern, replacement, text)` replaces every match.
Example 1 (python)
import re
emails = re.findall(r"[\w.]+@[\w.]+", "contact us at hi@x.com or sales@y.io")
print(emails)Output
['hi@x.com', 'sales@y.io']Extract every email-like substring.
Example 2 (python)
import re
clean = re.sub(r"\s+", " ", " too many\n\tspaces ").strip()
print(clean)Output
too many spacesCollapse whitespace.
Key points
- Import `re` module.
- Use raw strings `r"..."` for patterns.
- `findall` returns all matches, `search` returns the first.
- `sub` replaces matches.
๐ก Note: Regex is powerful but hard to read. For simple splitting/replacing, plain string methods are clearer.
