2016-07-15 188 views
-5

我试图创建一个正则表达式 以匹配不包含某些特定单词的字符串,并以一定的字像这样下一个字表:正则表达式不包含

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

例如:

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

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

+0

什么“不起作用”?它是否匹配不正确,你没有得到匹配等? –

+0

正则表达式的语法不正确,所以字符串不匹配 – nguyenngoc101

回答

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); 
    } 

希望这有助于:像样品!