Regular Expressions in Python
Regular expressions (regex) are powerful patterns for matching and manipulating text. They're used for validation (emails, phone numbers), searching, extracting data, and cleaning text.
Python's re module provides full regex support. Patterns can look complex at first, but they're built from simple building blocks.
We'll start with basics and build up with lots of examples.
Importing re and Basic Patterns
Import re and use raw strings (r"") for patterns to avoid escape issues.
Common characters:
- . – any character (except newline)
- ^ – start of string
- $ – end of string
- * – 0 or more
- + – 1 or more
- ? – 0 or 1
- \d – digit
- \w – word character
- \s – whitespace
Main re Methods
search() – first match anywhere match() – match at start findall() – all matches as list sub() – replace matches
Groups and Capturing
Use () to capture parts of the match.
Flags for Advanced Matching
re.IGNORECASE, re.MULTILINE, re.DOTALL etc.
Practical Examples
Validate simple email:
Extract phone numbers:
Quick Quiz
We have reviewed and checked the materials, but errors may still occur. The content is provided for educational purposes only, so use it at your own responsibility and verify with other sources if needed.
✨ Ask Lara — your AI study partner
Unlock personalized learning support. Lara can explain lessons, summarize topics, and answer your study questions — available from the Go plan and above.
Lara helps you learn faster — exclusive to ReadyTools Go, Plus, and Max members.


