Regex Cheat Sheet - Python

A comprehensive guide to regular expressions with patterns, examples, and explanations

Basic Metacharacters

.Any character except newline
\Escape character
|Alternation (OR)
^Start of string/line
$End of string/line

Character Classes

[abc]Any of a, b, or c
[^abc]Not a, b, or c
[a-z]Range from a to z
\dDigit [0-9]
\DNon-digit [^0-9]
\wWord character [a-zA-Z0-9_]
\WNon-word character
\sWhitespace
\SNon-whitespace

Quantifiers

*0 or more
+1 or more
?0 or 1
{n}Exactly n times
{n,}n or more times
{n,m}Between n and m times
*?Non-greedy 0 or more
+?Non-greedy 1 or more
??Non-greedy 0 or 1

Groups and Capturing

(pattern)Capturing group
(?:pattern)Non-capturing group
(?P<name>pattern)Named capturing group
\1Backreference to group 1
(?P=name)Named backreference

Lookarounds

(?=pattern)Positive lookahead
(?!pattern)Negative lookahead
(?<=pattern)Positive lookbehind
(?<!pattern)Negative lookbehind

Flags (re module)

re.IGNORECASECase insensitive matching
re.MULTILINE^ and $ match line breaks
re.DOTALLDot matches newline
re.VERBOSEAllow comments and whitespace
re.ASCIIASCII-only matching for \w, \b, \s, \d
re.UNICODEUnicode matching (default in Python 3)

Special Sequences

\AStart of string only
\ZEnd of string only
\bWord boundary
\BNon-word boundary
\numberOctal character
\xHex character

Raw Strings

r'\d+'Raw string - no escape processing
r'(?P<name>\w+)'Raw string for regex patterns