2015-02-07 532 views
0

我想匹配所有不包含單詞「you」的行。使用java正則表達式不包含單詞的匹配行

例子:

you are smart     
i and you not same    
This is not my fault   
Which one is yours    

結果:

This is not m fault 
Which one i yours    <-- this is match because the word is "yours" 

我使用\\b(?!you)\\w+試過,但它只是忽略了單詞 「你」。

回答

2

您需要使用單詞邊界和起始錨點。在啓動

"^(?!.*\\byou\\b).*" 

(?!.*\\byou\\b)負先行斷言,通過單詞邊界圍成的串you將不會出現在該行的任何地方。如果是,則.*然後匹配該對應行中的所有字符。注意負向前視中的.*非常重要,否則它只會在開始時檢查。 ^斷言我們在開頭,並且\b稱爲單詞字符和非單詞字符匹配的單詞邊界。

String s[] = {"you are smart", "i and you not same", "This is not my fault", "Which one is yours"}; 
for(String i : s) 
{ 
System.out.println(i.matches("^(?!.*\\byou\\b).*")); 
} 

輸出:

false 
false 
true 
true 

DEMO

OR

要匹配,除了所有的話you

"(?!\\byou\\b)\\b\\w+\\b" 

DEMO

String s = "you are smart\n" + 
     "i and you not same\n" + 
     "This is not my fault\n" + 
     "Which one is yours"; 
Matcher m = Pattern.compile("(?m)^(?!.*\\byou\\b).*").matcher(s); 
while(m.find()) 
{ 
    System.out.println(m.group()); 
} 

輸出:

This is not my fault 
Which one is yours 
+0

添加單詞邊界是在字符串中的一個,但不在一行中。 – newbie 2015-02-07 04:11:45

+0

@newbie看到我的更新。很難預測你的需求。請用預期輸出更新您的問題。 – 2015-02-07 04:14:54

+0

我刪除了我的答案和('+ 1')你,我不認爲OP知道他/她想要什麼。 – hwnd 2015-02-07 04:38:35

0

修改模式

\\b(?!you\\b)\\w+ 

you

相關問題