Understanding Zero-Width Assertions
You'll learn what zero-width assertions are and how they match positions in a string without consuming characters.
When you've been using regex patterns so far, most elements "consume" characters—they match actual text and move the matching position forward. But zero-width assertions are different: they're like invisible checkpoints that verify conditions at a specific position without eating any characters.
What Are Zero-Width Assertions?
Think of them as "looking around" from your current position in the string. You peek ahead (lookahead) or behind (lookbehind) to check if certain patterns exist, but you don't actually include those characters in your match. The matching cursor doesn't advance.
There are four types:
- Positive Lookahead
(?=...): Asserts that what follows matches the pattern - Negative Lookahead
(?!...): Asserts that what follows does not match the pattern - Positive Lookbehind
(?<=...): Asserts that what precedes matches the pattern - Negative Lookbehind
(?<!...): Asserts that what precedes does not match the pattern
Why "Zero-Width"?
These assertions match positions, not characters. When a lookahead or lookbehind succeeds, the match length is zero—you haven't moved forward or backward in the string. You've simply verified a condition at that spot.
Example Concept
Imagine matching "Java" only when followed by "Script" but without including "Script" in your capture: Java(?=Script). The lookahead checks that "Script" is there, but only "Java" gets matched.
Or finding a number preceded by a dollar sign: (?<=\$)\d+ matches the digits but not the $ itself.
Key Takeaway:
Zero-width assertions (lookahead and lookbehind) let you match positions based on surrounding context without consuming characters—perfect for conditional matching and precise text extraction.