Java Language Regular Expressions Not matching a given string


Example

To match something that does not contain a given string, one can use negative lookahead:

Regex syntax: (?!string-to-not-match)

Example:

//not matching "popcorn"
String regexString = "^(?!popcorn).*$";
System.out.println("[popcorn] " + ("popcorn".matches(regexString) ? "matched!" : "nope!"));
System.out.println("[unicorn] " + ("unicorn".matches(regexString) ? "matched!" : "nope!"));

Output:

[popcorn] nope!
[unicorn] matched!