Advanced Regex: Lookaheads, Lookbehinds & Named Groups

Lookaheads, lookbehinds, and other advanced regex features for power users.

advancedtechniquespatterns

Advanced Regex

Once you've mastered the basics, these advanced features unlock even more power.

Lookahead

Match only if followed by pattern (doesn't consume):

// Positive lookahead (?=)
/foo(?=bar)/ // "foo" only if followed by "bar"
"foobar".match(/foo(?=bar)/) // ["foo"]

// Negative lookahead (?!)
/foo(?!bar)/ // "foo" only if NOT followed by "bar"
"foobaz".match(/foo(?!bar)/) // ["foo"]

Lookbehind

Match only if preceded by pattern:

// Positive lookbehind (?<=)
/(?<=@)\w+/ // Word after @
"user@domain".match(/(?<=@)\w+/) // ["domain"]

// Negative lookbehind (?<!)
/(?<!\d)\d{3}(?!\d)/ // 3 digits not part of larger number

Named Groups

const pattern = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
const match = "2024-01-15".match(pattern);

console.log(match.groups.year); // "2024"
console.log(match.groups.month); // "01"
console.log(match.groups.day); // "15"

Non-Greedy Matching

// Greedy (default): matches as much as possible
/<.>/g.exec("<a><b>") // ["<a><b>"]

// Non-greedy: matches as little as possible
/<.
?>/g.exec("<a><b>") // ["<a>"]

Practical Examples

// Password validation (complex)
/^(?=.[a-z])(?=.[A-Z])(?=.\d)(?=.[@$!%?&])[A-Za-z\d@$!%?&]{8,}$/

// Extract domain from URL
/(?<=:\/\/)[^/]+/

// Match balanced quotes
/"([^"\\]|\\.)*"/

// Validate credit card (basic)
/^\d{4}[- ]?\d{4}[- ]?\d{4}[- ]?\d{4}$/