Regular Expressions in Python
Complete guide to Python Regular Expressions using the re module: syntax, patterns, flags, matching, searching, replacing, groups, quantifiers, anchors, lookarounds, validation, and real-world use cases.
Introduction to Regular Expressions
A regular expression (regex) is a pattern used for matching and manipulating text.
1. Basic Matching with re
Use re.search() for matching.
Creating Regex Patterns
Patterns are plain strings passed to re functions.
1. Raw Strings (r"")
Avoid escape issues.
Core re Functions
Python provides multiple regex functions.
1. search() vs match()
Difference in behavior.
2. findall()
Return all matches.
3. sub()
Replace matches.
4. finditer()
Iterator of match objects.
Regex Flags
Modify pattern behavior using flags.
1. Common Flags
IGNORECASE, MULTILINE, DOTALL.
Character Classes
Match specific character sets.
1. Common Classes
\d, \w, \s
Quantifiers
Control repetition.
1. Common Quantifiers
* + ? {n,m}
Anchors
Match positions in string.
1. ^ and $
Start and end anchors.
Groups & Named Groups
Capture sub-patterns.
1. Capturing Groups
Access with group().
2. Named Groups
Use (?P<name>).
Lookahead & Lookbehind
Match based on surrounding context.
1. Positive Lookahead
Use (?=...).
2. Positive Lookbehind
Use (?<=...).
Validation Examples
Common real-world patterns.
1. Basic Email Validation
Simple pattern.
2. Numeric String Validation
Digits only.