Python re module · dark mode for fast scanning · visual pattern recognition
Basic Syntax literals & specials
Pattern
Matches
Example
abc
literal characters
“abc” in “xabcx”
\d
any digit (0‑9)
\d → 7
\D
any non‑digit
\D → a
\w
word char [A‑Za‑z0‑9_]
\w → _
\W
non‑word char
\W → space
\s
whitespace
\s → \t
\S
non‑whitespace
\S → x
.
any char (except newline)
. → a
\.
literal dot (escape)
\. → .
Character Classes sets & ranges
Pattern
Matches
Example
[aeiou]
any vowel
[aeiou] → e
[A-Z]
uppercase letter
[A-Z] → B
[^0-9]
any char except digit
[^0-9] → x
[a-z0-9]
lowercase or digit
→ g or 5
[a-zA-Z]
any letter (case‑insens.)
→ Z
Quantifiers how many
Symbol
Meaning
Example
*
0 or more (greedy)
a* → “” or “aaa”
+
1 or more
\d+ → “42”
?
0 or 1 (optional)
colou?r → color/colour
{n}
exactly n
\d{3} → “123”
{n,}
n or more
\d{2,} → “12345”
{n,m}
between n and m
\d{2,4} → “123”
*? lazy
0+ (few as possible)
a+? → “a” in “aaa”
Anchors positions
Symbol
Matches
Example
^
start of string (or line)
^Hello → “Hello” at start
$
end of string (or line)
world$ → “…world” at end
\b
word boundary
\bcat\b → “cat” not “catalog”
\B
not word boundary
\Bcat\B → “catalog” (inside)
Groups & Capturing
Pattern
Matches
Example
(abc)
capturing group
(\d{3})-(\d{2}) → captures
(?:abc)
non‑capturing
(?:https?://) → no store
\1
backreference to group 1
(a)\1 → “aa”
(?P<name>...)
named group
(?P<year>\d{4}) → .group(‘year’)
Lookarounds zero‑width
Pattern
Meaning
Example
(?=...)
positive lookahead
\d(?=px) → 5 in “5px”
(?!...)
negative lookahead
\d(?!px) → 5 in “5em”
(?<=...)
positive lookbehind
(?<=\$)\d+ → 100 in “$100”
(?<!...)
negative lookbehind
(?<!\$)\d+ → 100 in “€100”
Common Flags Python re
Flag
Effect
Usage
re.I
case‑insensitive
re.search(r’hello’, ‘HELLO’, re.I)
re.M
^ and $ match lines
re.M makes ^ per line
re.S
. matches newline
allows cross‑line matching
re.X
verbose (comments + spaces)
multi‑line readable patterns
re.A
\w, \d, \s ASCII only
avoid Unicode matches
Python re – Quick Usage
# match from start
m = re.match(r’^(\w+)_normal\.png$’, filename)
if m: prefix = m.group(1)
# search anywhere
if re.search(r’\d{3}’, text): …
# find all matches
matches = re.findall(r’\b[A-Z]+\b’, text)
# find all with groups
pairs = re.findall(r'(\w+)=(\d+)’, data)
# substitute
new = re.sub(r’_normal\.png$’, ‘_AO.png’, f, re.I)
# compile for performance
pat = re.compile(r’^.*_normal\.png$’, re.I)
Pitfalls watch out!
• . does not match newline – use re.S
• \b treats _ as word character (because \w includes _)
• Greedy vs lazy: <.*> matches "<b>"? No – it’s greedy and takes "<b>" (first < to last >). Use <.*?> for minimal
• Raw strings (r'') avoid escaping backslashes
• re.match checks only at start; use re.search for anywhere
• Lookbehinds must be fixed‑width in Python (no + or * inside)