您需要使用单词边界和起始锚点。在启动
"^(?!.*\\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