Regular Expressions in Python
A regular expression (regex) is a compact pattern language for matching, searching, and manipulating text based on its shape rather than an exact literal string — matching "any digit," "one or more letters," or an email-like pattern, for instance. Python's built-in re module provides the tools to apply these patterns against actual text.
import re
Brings in the module, part of the standard library.
re.search(pattern, text)
Looks for the pattern anywhere in text, returning a match object if found, or None if not.
re.findall(pattern, text)
Returns every non-overlapping match as a list of strings.
re.sub(pattern, replacement, text)
Replaces every match with replacement, returning the resulting new string.
Special characters build the pattern language
A digit placeholder, a "one or more" quantifier, and parentheses to capture part of a match.
import re text = "Call me at 123-456-7890 or 987-654-3210" match = re.search(r"\d{3}-\d{3}-\d{4}", text)print(match.group()) all_numbers = re.findall(r"\d{3}-\d{3}-\d{4}", text)print(all_numbers) masked = re.sub(r"\d{3}-\d{3}-\d{4}", "[phone number]", text)print(masked)Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Python yourself — building beats watching.