2026-02-15|Plugins

Advanced Regex Techniques: Lookaheads, Named Groups, and More

Lookahead and Lookbehind Assertions

Lookahead and lookbehind assertions are powerful regex features that allow you to match patterns based on what comes before or after, without including those surrounding characters in the match.

Positive Lookahead (?=...)

Matches a pattern only if it is followed by another pattern:

/\d+(?=px)/  // Matches "12" in "12px" but not in "12em"

Negative Lookahead (?!...)

Matches a pattern only if it is NOT followed by another pattern:

/\d+(?!px)/  // Matches "12" in "12em" but not in "12px"

Lookbehind Assertions

Positive lookbehind (?<=...) matches if preceded by a pattern:

/(?<=\$)\d+/  // Matches "100" in "$100"

Negative lookbehind (?<!...) matches if NOT preceded:

/(?<!\$)\d+/  // Matches "100" in "100USD" but not in "$100"

Named Groups and Backreferences

Named groups make complex patterns more readable:

/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/

You can reference named groups later in the pattern or in replacements:

str.replace(/(?<year>\d{4})-(?<month>\d{2})/, '$<month>/$<year>')

Non-Greedy Quantifiers

By default, quantifiers are greedy (match as much as possible). Add ? for non-greedy behavior:

/".+?"/   // Matches the shortest string between quotes
/".*"/    // Matches the longest string (greedy)

Flags and Advanced Options

  • s (dotAll): Makes . match newlines
  • m (multiline): Makes ^ and $ match line boundaries
  • u (unicode): Enables full Unicode support
/^[\w\s]+$/ms  // Matches multiline text

Practical Examples

Validate Complex Email

/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/

Match HTML Tags (Simple)

/<([a-z]+)([^<]*)>(.*?)<\/\1>/gi

Extract URLs from Text

/https?:\/\/[\w\-]+(\.[\w\-]+)+[\w\-.,@?^=%&:/~+#]*/g