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 TypeSyntaxDescription / 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
SyntaxTypePurpose
(?:pattern)Non-capturing GroupGroup expressions without creating a numbered backreference
(?>pattern)Atomic GroupPrevent backtracking inside the group once matched
(?i)Inline FlagEnable 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 re module); 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.