REGEX CHEAT SHEET (Python & Cybersecurity
Edition)
1. BASICS — Character Matching
.
Any character (except newline)
a.c → abc, axc
[abc]
Any one of a, b, or c
[ch]at → cat, hat
[^abc]
Any character except a, b, or c
[^0-9] → any non-digit
\d / \D
Digit / Non-digit
\d\d → 42
\w / \W
Word / Non-word character
\w+ → user_01
\s / \S
Whitespace / Non-whitespace
\s+ → ' '
2. QUANTIFIERS — How Many Times
*
0 or more
lo*l → lol, loool
+
1 or more
lo+l → lol, loool
?
0 or 1
colou?r → color, colour
{n}
Exactly n
\d{4} → 2025
{n,}
n or more
\d{2,} → 12, 1234
{n,m}
Between n and m
\d{2,4} → 12, 1234
3. ANCHORS — Start / End / Boundaries
^
Start of string
^Hello → Hello world
$
End of string
end$ → the end
\b
Word boundary
\bcat\b → cat but not bobcat
\B
Non-boundary
\Bcat → bobcat
4. GROUPS & CAPTURING
(abc)
Capturing group
(dog)+ → dogdog
(?:abc)
Non-capturing group
(?:cat|dog) → no saved group
(a|b)
Alternation (OR)
(cat|dog) → cat or dog
(?P<name>...)
Named group
(?P<ip>\d+\.\d+)
\1, \2
Backreference
(\w+)\s+\1 → repeated word
5. ESCAPES — Special Characters
\.
Literal dot
a\.b → a.b
\?
Literal ?
why\? → why?
\+
Literal +
c\+\+ → c++
\*
Literal *
\*bold\* → *bold*
6. LOOKAHEADS & LOOKBEHINDS
(?=...)
Positive lookahead
\w+(?=\.) → word before dot
(?!...)
Negative lookahead
\w+(?!\.) → word not before dot
(?<=...)
Positive lookbehind
(?<=@)\w+ → word after @
(?<!...)
Negative lookbehind
(?<!@)\w+ → word not after @
7. FLAGS (Python-specific)
re.I
Ignore case
re.search('hello', text, re.I)
re.M
Multiline
Makes ^ and $ work per line
re.S
Dot matches newline
—
re.X
Verbose mode
Ignore spaces/comments