…Everything from chatGPT…
Let’s say we want to validate a password that meets the following criteria:
- At least 8 characters long
- Contains a combination of letters (both uppercase and lowercase), numbers, and special characters
- Does not contain the word “password” anywhere
We can use negative lookahead to implement this validation. Here’s an example using JavaScript:
javascriptCopy code
const password = "SecurePass123!";
const regex = /^(?!.*password).*$/;
if (regex.test(password) && password.length >= 8) {
console.log("Password is valid.");
} else {
console.log("Password is invalid.");
}
In this example, the regular expression ^(?!.*password).*$
is used. Let’s break it down:
-
^
: Matches the start of the string. -
(?!.*password)
: Negative lookahead assertion that checks if the string does not contain the word “password” anywhere. The.*
matches any characters (except newline), so.*password
matches any characters followed by “password”. -
.*
: Matches any characters (except newline). -
$
: Matches the end of the string.
By using the negative lookahead (?!.*password)
, we ensure that the string does not contain the word “password”. If the password meets this condition and is at least 8 characters long (checked separately), it is considered valid.
Note that this is a basic example, and password requirements can vary depending on specific needs. However, it demonstrates the use of negative lookahead to exclude certain patterns from matching.