Negative Lookahead Syntax: (?!...)
You'll learn how to use negative lookahead to exclude unwanted patterns from your matches.
What Is Negative Lookahead?
Negative lookahead is a zero-width assertion that checks if a pattern does not follow the current position. It's written as (?!...) where ... is the pattern you want to exclude. If that pattern would match at the current position, the assertion fails and the overall match fails.
Think of it like a "not allowed ahead" sign: you're checking the road ahead without actually moving forward. If you see the forbidden pattern, you reject the current path.
How It Works
Unlike positive lookahead (?=...) which succeeds when a pattern is found ahead, negative lookahead succeeds when a pattern is not found ahead. The assertion doesn't consume any characters—it only checks.
Syntax: (?!pattern)
For example, \d+(?!0) matches a number not followed by zero. It ensures that whatever digit sequence you're matching doesn't have a zero immediately after it.
Pattern p = Pattern.compile("\\d+(?!0)");
Matcher m1 = p.matcher("123"); // matches "123" (no 0 follows)
Matcher m2 = p.matcher("1230"); // matches "123" (excluding the 0)
Matcher m3 = p.matcher("120"); // doesn't match "12" (0 follows immediately)
Practical Applications
Negative lookahead shines in validation scenarios. Want a password that contains letters but not a specific sequence? Use (?!.*password) at the start. Need to match words except certain reserved ones? Negative lookahead lets you express exclusions elegantly.
Key Takeaway: Negative lookahead (?!...) asserts that a pattern does NOT follow the current position, enabling you to exclude specific patterns without consuming characters—perfect for validation and exclusionary matching logic.