Python Regex Patterns (re module) Cheat Sheet
Reference guide for Python regular expressions. Learn match, search, findall, sub, and essential regex patterns.
Core re Module Methods
Standard function interfaces in the re library for text queries.
| Method | Syntax | Description |
|---|---|---|
| search() | re.search(pattern, string) | Scans the input string to locate the first location where the regex pattern matches. |
| match() | re.match(pattern, string) | Determines if the regex pattern matches starting at the beginning of the string. |
| findall() | re.findall(pattern, string) | Finds all non-overlapping matches of the pattern, returning a list of matches. |
| finditer() | re.finditer(pattern, string) | Returns an iterator yielding MatchObject instances for all matches. |
| sub() | re.sub(pattern, repl, string) | Replaces all occurrences of the pattern in the string with repl. |
| compile() | re.compile(pattern) | Compiles a regular expression pattern into a regular expression object for reuse. |
Regex Metacharacters & Shorthands
Building blocks for constructing search patterns.
| Method | Syntax | Description |
|---|---|---|
| . | Match any character | Matches any single character except a newline. |
| ^ / $ | Anchor start / end | Matches the start of string (^) and end of string ($). |
| * / + / ? | Quantifiers | Represents 0 or more (*), 1 or more (+), or 0 or 1 (?) repetitions. |
| \d | Digit character | Equivalent to class [0-9]. |
| \w | Alphanumeric character | Matches alphanumeric characters and underscores. |
| \s | Whitespace character | Matches spaces, tabs, and newline characters. |
Frequently Asked Questions
What is the difference between re.match() and re.search()?
re.match() checks for a match only at the beginning of the string, while re.search() scans the entire string for a match anywhere.
How do I capture group outputs in a regex match?
Use parentheses () in your pattern to define groups, and retrieve them using match_obj.group(1), match_obj.group(2), etc.
Keep Learning
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python Regex
Master Regular Expressions (Regex) in Python. Learn to search, match, split, and substitute string data using the built-in re library.
How to Sort a List in Python
Learn how to sort a list in Python using the sort() method and the sorted() function. Discover custom key sorting and reverse order examples.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.