Negative Lookahead (?!)
Negative lookahead matches only when a pattern is NOT followed by something specific.
Syntax
pattern(?!lookahead) matches "pattern" only if NOT followed by "lookahead".
Matches numbers that are NOT followed by " dollars".
Exercises
Excluding Specific Patterns
Practical Examples
Combining with Positive Lookahead
You can use both positive and negative lookaheads:
Password Validation Example
A complex example combining concepts:
This password must:
- Have uppercase
(?=.*[A-Z]) - Have lowercase
(?=.*[a-z]) - Have a digit
(?=.*\d) - NOT contain "password"
(?!.*password) - Be at least 8 characters
.{8,}
Practice Playground
Try:
(?!test)\w+- not starting with test\w+(?!_user)- not ending with _user(?!.*test).*admin.*- admin without test
Key Takeaways
(?!pattern)is a negative lookahead- Matches only when NOT followed by the pattern
- Zero-width: doesn't consume characters
- Useful for exclusion logic
- Combine with positive lookaheads for complex rules

