您需要使用單詞邊界和起始錨點。在啓動
"^(?!.*\\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
添加單詞邊界是在字符串中的一個,但不在一行中。 – newbie 2015-02-07 04:11:45
@newbie看到我的更新。很難預測你的需求。請用預期輸出更新您的問題。 – 2015-02-07 04:14:54
我刪除了我的答案和('+ 1')你,我不認爲OP知道他/她想要什麼。 – hwnd 2015-02-07 04:38:35