我想匹配所有不包含“you”一词的行。
示例:
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+
,但它只是忽略了“you”这个词。
最佳答案
您需要使用单词边界和起始 anchor 。
"^(?!.*\\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
或者
匹配除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
关于java - 使用 java regex 匹配不包含单词的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28378394/