import re
re.search(pattern, string)
re.findall(pattern, string)
Example
import re
text ="Contact: [email protected] or [email protected]"
emails = re.findall(r"[\w.]+@[\w.]+\.\w+", text)print(emails)# Named groups
log ="2026-04-04 ERROR: Connection timeout"match= re.match(r"(?P<date>[\d-]+) (?P<level>\w+): (?P<msg>.+)", log)ifmatch:print(match.group("level"),match.group("msg"))
Note Always use raw strings (r'...') for regex patterns. For repeated use, compile with re.compile() for performance. Use re.VERBOSE for readable multi-line patterns.
Note Each branch ends with ;;. Patterns support globbing and | for alternatives. case is cleaner than long if/elif chains when matching a single variable against many values. *) is the default/catch-all branch.
Frequently asked questions
How does Python handle pattern matching?
This task is covered in 2 stacks on this page: Python, Bash & Linux. The "match / case (Structural Pattern Matching)" snippet in Python uses `match subject:`.
Which code does the Python example use?
The "match / case (Structural Pattern Matching)" snippet uses `match subject:`, from the Control Flow section of the Python cheat sheet.
Which stacks cover "pattern matching" on this page?
Python, Bash & Linux. Together they hold 3 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "match / case (Structural Pattern Matching)": match/case (Python 3.10+) is structural pattern matching, not just a switch. It can destructure dicts, sequences, and objects in the pattern.