java - 使用 java regex 匹配不包含单词的行

标签 java regex

我想匹配所有不包含“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

DEMO

或者

匹配除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

关于java - 使用 java regex 匹配不包含单词的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28378394/

相关文章:

java - Netty单元测试: How to test invocations on the Channel object that is part of the passed ChannelHandlerContext?

java - 使用java在网络打印机中打印pdf

java - 如何处理 URL(Spring、REST、CXF)中的转义字符(管道 |)?

python - Python 中的负回顾 RE

python - 使用正则表达式 python 捕获版本号

java - 发现不兼容的类型 : void, 出了什么问题?

c# - HTML敏捷包: get all elements by class

php - 以任意顺序匹配子模式

Javascript 正则表达式 - 匹配句子并忽略引号中的句号

java - 在 Java 中比较两个单独列表中的项目