Negative Lookbehind Syntax: (?<!...)
You'll learn how to assert that a specific pattern does not appear immediately before your match position, enabling precise boundary control in your regular expressions.
What Is Negative Lookbehind?
A negative lookbehind (?<!...) is a zero-width assertion that succeeds only if the text immediately before the current position does not match the specified pattern. Like other lookbehinds, it doesn't consume any characters—it just checks a condition.
Think of it as a "not-preceded-by" guard: "I'll only match here if what comes before is not X."
Syntax
(?<!pattern)
The pattern inside the lookbehind must be fixed-width in Java (no variable-length quantifiers like * or +).
When to Use Negative Lookbehind
Use negative lookbehind when you need to match something only if it's not preceded by a specific pattern:
Pattern pattern = Pattern.compile("(?<!\\$)\\d+");
Matcher matcher = pattern.matcher("Price: $100 and 200 items");
while (matcher.find()) {
System.out.println("Found: " + matcher.group());
}
// Output:
// Found: 00
// Found: 200
Here, (?<!\\$)\\d+ matches digits not preceded by a dollar sign. Notice it matched "00" from "`) and "200" entirely.
Combining with Other Assertions
Pattern pattern = Pattern.compile("(?<!@)\\b\\w+");
Matcher matcher = pattern.matcher("user@example but standalone");
while (matcher.find()) {
System.out.println(matcher.group());
}
// Matches words not preceded by @
Key Takeaway: Negative lookbehind (?<!...) asserts that a pattern does not precede the current position, letting you exclude matches based on what comes before without consuming characters.