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.

MethodSyntaxDescription
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.

MethodSyntaxDescription
.Match any characterMatches any single character except a newline.
^ / $Anchor start / endMatches the start of string (^) and end of string ($).
* / + / ?QuantifiersRepresents 0 or more (*), 1 or more (+), or 0 or 1 (?) repetitions.
\dDigit characterEquivalent to class [0-9].
\wAlphanumeric characterMatches alphanumeric characters and underscores.
\sWhitespace characterMatches 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.