Python Regex Cheatsheet
Regular Expression Basics Regular Expression Character Classes Regular Expression Flags
. Any character except newline [ab-d] One character of: a, b, c, d i Ignore case
a The character a [^ab-d] One character except: a, b, c, d m ^ and $ match start and end of line
ab The string ab [\b] Backspace character s . matches newline as well
a|b a or b \d One digit x Allow spaces and comments
a* 0 or more a's \D One non-digit L Locale character classes
\ Escapes a special character \s One whitespace u Unicode character classes
\S One non-whitespace (?iLmsux) Set flags within regex
Regular Expression Quantifiers
\w One word character
* 0 or more Regular Expression Special Characters
\W One non-word character
+ 1 or more \n Newline
? 0 or 1 Regular Expression Assertions \r Carriage return
{2} Exactly 2 ^ Start of string \t Tab
{2, 5} Between 2 and 5 \A Start of string, ignores m flag \YYY Octal character YYY
{2,} 2 or more $ End of string \xYY Hexadecimal character YY
(,5} Up to 5 \Z End of string, ignores m flag
Regular Expression Replacement
Default is greedy. Append ? for reluctant. \b Word boundary
\g<0> Insert entire match
\B Non-word boundary
\g<Y> Insert match Y (name or number)
Regular Expression Groups
(?=...) Positive lookahead
\Y Insert group numbered Y
(...) Capturing group
(?!...) Negative lookahead
(?P<Y>...) Capturing group named Y
(?<=...) Positive lookbehind
(?:...) Non-capturing group
(?<!...) Negative lookbehind
\Y Match the Y'th captured group
(?()|) Conditional
(?P=Y) Match the named group Y
(?#...) Comment