我希望匹配所有不包含单词"你"。
的行。示例:
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+
,但它只是忽略了单词&#34;你&#34;。
答案 0 :(得分: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
OR
匹配除you
"(?!\\byou\\b)\\b\\w+\\b"
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
答案 1 :(得分:0)
将您的模式修改为
\\b(?!you\\b)\\w+
在you