๐งฉ Python Regex Tutorial with Examples
Regular expressions (regex) in Python use the re module to search, match, and manipulate strings with powerful pattern rules.
Use raw strings (r'...') for regex patterns to avoid Python's own backslash interpretation conflicts.
๐ป Code Example:
import re # 1. re.search() โ find pattern anywhere in string text = "Pynfinity was founded by santoshtvk in 2024" match = re.search(r'\d{4}', text) print(match.group()) # 2024 # 2. re.findall() โ get ALL matches as a list emails = "contact: admin@pynfinity.com, tvk@gmail.com" found = re.findall(r'[\w.]+@[\w.]+', emails) print(found) # ['admin@pynfinity.com', 'tvk@gmail.com'] # 3. re.sub() โ replace matches cleaned = re.sub(r'\s+', ' ', "too many spaces") print(cleaned) # 'too many spaces' # 4. re.match() โ match at start of string only result = re.match(r'^Pynfinity', text) print(bool(result)) # True # 5. Groups โ extract specific parts url = "https://pynfinity.com/pebbles/python-regex" pattern = r'https?://(\S+)/(\S+)/(\S+)' m = re.search(pattern, url) if m: print(m.group(1), m.group(2), m.group(3))
| Concept | Key Takeaway |
|---|---|
| re.match() | Match at the START of string only |
| re.search() | Match ANYWHERE in string โ returns first match |
| re.findall() | Returns ALL matches as a list |
| re.sub() | Replace matches with a new string |
| re.compile() | Pre-compile a pattern for reuse (faster in loops) |
Keep exploring and happy coding! ๐