正则表达式不包含单词列表

时间:2016-07-15 02:40:19

标签: java regex

我正在尝试创建正则表达式 匹配一个字符串,该字符串不包含某些特定单词并跟随某个单词,如下所示:

(?<!(state|government|head).*)of

例如:

state of -> not match
government of -> not match
Abc of -> match

但它不起作用。我不知道为什么,请帮我解释一下。

1 个答案:

答案 0 :(得分:0)

您可以将此正则表达式与否定前瞻一起使用。样本如:

     public static void main(String[] args) {

        Pattern pattern = Pattern.compile("^(?!state|government|head).*$");
        String s = "state of";
        Matcher matcher = pattern.matcher(s);
        boolean bl = matcher.find();
        System.out.println(bl);

        s = "government of";
        matcher = pattern.matcher(s);
        bl = matcher.find();
        System.out.println(bl);

        s = "Abc of";
        matcher = pattern.matcher(s);
        bl = matcher.find();
        System.out.println(bl);
    }

希望这有帮助!

相关问题