What is a negative lookahead?
A negative lookahead assertion in regular expression (RegEx) checks if the pattern inside the lookahead does not match with the input string.
The syntax for the negative lookahead is (?! pattern).
(?!) - negative lookahead
(pattern) - the pattern must not match with the input string
Use case
Consider a website that uses a synthetic monitor. You don't want the word Error in the website content. If the content has the word Error, then the monitor will trigger an alert. This can be achieved using the negative lookahead in RegEx.
Example
Exclude Error from the webpage.
Input for Should match regular expression: ^(?s)(?!.*Error).*$
Explanation for the above RegEx:
^ — Start of the string
(?s) — Enables DOTALL mode, making newline characters match
(?!.*Error) — Negative lookahead ensuring Error is not in the string
.* — Matches any sequence of characters (including newlines)
$ — End of the string
When the above RegEx is entered in the content checks, it checks for the word Error in the webpage. When the word Error is encountered, the monitor triggers an alert message.
Example 1: You've successfully logged in.
Note: The word Error is not available in the above response. So, the RegEx should match, and the monitor will stay up.
Example 2: Error with a user name and password.
Note: The word Error is in the above response. So, the RegEx should not match, and the monitor will trigger an alert.