不匹配給定的字串

要匹配包含給定字串的內容,可以使用否定前瞻:

正規表示式語法:(?!string-to-not-match)

例:

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

輸出:

[popcorn] nope!
[unicorn] matched!