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/lineCharacter Classes
[abc]
Any of a, b, or c[^abc]
Not a, b, or c[a-z]
Range from a to z\d
Digit [0-9]\D
Non-digit [^0-9]\w
Word character [a-zA-Z0-9_]\W
Non-word character\s
Whitespace\S
Non-whitespaceQuantifiers
*
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 1Groups and Capturing
(pattern)
Capturing group(?:pattern)
Non-capturing group(?P<name>pattern)
Named capturing group\1
Backreference to group 1(?P=name)
Named backreferenceLookarounds
(?=pattern)
Positive lookahead(?!pattern)
Negative lookahead(?<=pattern)
Positive lookbehind(?<!pattern)
Negative lookbehindFlags (re module)
re.IGNORECASE
Case insensitive matchingre.MULTILINE
^ and $ match line breaksre.DOTALL
Dot matches newlinere.VERBOSE
Allow comments and whitespacere.ASCII
ASCII-only matching for \w, \b, \s, \dre.UNICODE
Unicode matching (default in Python 3)Special Sequences
\A
Start of string only\Z
End of string only\b
Word boundary\B
Non-word boundary\number
Octal character\x
Hex characterRaw Strings
r'\d+'
Raw string - no escape processingr'(?P<name>\w+)'
Raw string for regex patterns