Advanced Regex Patterns Cheat Sheet
Quick reference guide for Advanced Regex: Positive/Negative lookaheads, lookbehinds, named capture groups, and backreferences.
Languages
regex
regexp
lookahead
Advanced Regular Expressions (Regex) provide zero-width assertions, named capture groups, and backreferences for complex text matching logic.
Lookaround Assertions Reference
Lookarounds match a position without consuming characters in the match result (zero-width).
Table
| Lookaround Type | Syntax | Description / Match Condition |
|---|---|---|
| Positive Lookahead | (?=pattern) | Match if followed by pattern |
| Negative Lookahead | (?!pattern) | Match if NOT followed by pattern |
| Positive Lookbehind | (?<=pattern) | Match if preceded by pattern |
| Negative Lookbehind | (?<!pattern) | Match if NOT preceded by pattern |
Advanced Pattern Examples
regex
# 1. Match password with >=8 chars, containing 1 digit and 1 uppercase letter
^(?=.*[A-Z])(?=.*\d).{8,}$
# 2. Extract price number preceded by dollar sign ($) without matching symbol
(?<=\$)\d+(\.\d{2})?
# 3. Match word NOT followed by "bar"
foo(?!bar)
# 4. Named Capture Groups (?<name>pattern)
(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})
# 5. Backreference (\1 or \k<name>) to match repeated HTML tag
<(?<tag>\w+)>(.*?)</\k<tag>>
Atomic Groups & Non-Capturing Groups
Table
| Syntax | Type | Purpose |
|---|---|---|
(?:pattern) | Non-capturing Group | Group expressions without creating a numbered backreference |
(?>pattern) | Atomic Group | Prevent backtracking inside the group once matched |
(?i) | Inline Flag | Enable case-insensitive matching for sub-pattern |
Common Pitfalls & Tips
[!WARNING] Fixed-length lookbehinds are required in some Regex engines (such as JavaScript engines before ES2018 or Python
remodule); variable-length lookbehinds (e.g.(?<=a+)) may throw syntax errors.
[!TIP] Use non-capturing groups
(?:...)when grouping OR conditions (e.g.,(?:cat|dog)) to avoid performance overhead from creating unnecessary capture groups.