2015-02-07 533 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

相关问题