Python's regular expressions are powered by the built-in re module. While it shares many similarities with other regex engines, Python brings its own set of functions and best practices.
Whether you're data scraping, cleaning text datasets, or just parsing logs, this python regex cheat sheet will get you up and running fast.
Importing the Module
To get started, simply import the module:
import re
The Core Functions
1. re.search()
Scans through a string, looking for any location where the regex produces a match. It returns a match object on success, or None on failure.
pattern = r"python regex match"
text = "I want a python regex match example."
match = re.search(pattern, text)
if match:
print("Found:", match.group())
2. re.match()
Unlike search(), match() checks for a match only at the beginning of the string.
# This will return None because "Python" is not at the start
re.match(r"Python", "Hello Python")
3. re.findall()
Returns all non-overlapping matches of the pattern in a string, as a list of strings.
text = "user1@email.com, user2@email.com"
emails = re.findall(r"[\w.-]+@[\w.-]+", text)
# ['user1@email.com', 'user2@email.com']
4. re.sub()
Replaces one or many matches with a string.
text = "Remove numbers 123 from here 456"
clean_text = re.sub(r"\d+", "", text)
# "Remove numbers from here "
Raw Strings are Crucial
Always prefix your regex strings in Python with r (e.g., r"\n"). This tells Python to treat the string as a "raw string," preventing Python from trying to evaluate escape characters before passing them to the regex engine.
Try it out visually
Writing Python regex requires a lot of testing. We highly recommend using a visualizer to see exactly how your groups are capturing. Try our live visualizer below!
Need help with another language? Check out our JavaScript Regex Match Guide. And for all your debugging needs, don't forget to bookmark RegexRef by one4.dev, the best regex visualizer on the web.