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)
if match:
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.