2016-07-15 189 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); 
    } 

希望這有助於:像樣品!