Advanced Features

Lookaheads and Lookbehinds

Lookahead

PatternMeaning
(?=...)Positive lookahead
(?!...)Negative lookahead

Examples:

\d+(?=px) # Matches digits followed by "px": "100px" → captures "100"
\d+(?!px) # Matches digits NOT followed by "px"

Lookbehind

PatternMeaning
(?<=...)Positive lookbehind
(?<!...)Negative lookbehind

Examples:

(?<=\$)\d+ # Matches digits preceded by $: "$100" → captures "100"
(?<!\\)prod # Matches "prod" NOT preceded by backslash

Negative Lookbehind Example

(?<!\\)prod

In plain language: Matches “prod” only when it is NOT preceded by a backslash.

Examples:

  • “Let’s calculate the prod of these numbers” → “prod” would be matched
  • “Use the \prod symbol for product notation” → “prod” would NOT be matched

The negative lookbehind ensures capturing instances of “prod” that aren’t part of a command or escaped sequence.

What is an Escaped Sequence?

An escaped sequence is a character preceded by a backslash (\) that has special meaning:

  • \n - newline
  • \t - tab
  • \\ - literal backslash
  • \prod - LaTeX command for product symbol (∏)

The backslash “escapes” the normal meaning of the following character.

Backreferences

Reference previously captured groups:

(\w+)\s+\1 # Matches repeated words: "hello hello"
(['"]).*?\1 # Matches quoted strings: "hello" or 'world'
  • \1 refers to first captured group
  • \2 refers to second captured group
  • etc.

Greedy Vs Lazy Quantifiers

GreedyLazyBehavior
**?Match 0+ (lazy)
++?Match 1+ (lazy)
???Match 0-1 (lazy)
{n,m}{n,m}?Match n-m (lazy)

Example:

<div>Hello</div><div>World</div>
<div>.*</div> # Greedy: Matches entire string
<div>.*?</div> # Lazy: Matches "<div>Hello</div>" only