java - 一个正则表达式问题

标签 java regex

在 Java 的正则表达式中,我想匹配任何包含单词“Mary”和单词“are”的句子,但在“Mary”和“are”之间不包含“Bob”。

Eg: Mary and Rob are married - MATCH
Eg: Mary and John and Michael became good friends and are living together <- MATCH
Eg: Mary, Rob and Bob are dead <- does not MATCH

有什么想法吗?

最佳答案

一个更短的版本:

(?m)^.*\bMary\b((?!\bBob\b).)*\bare\b.*$


public class Main {
    public static void main(String[] args) {
        String[] tests = {
                "Mary and Rob are married",
                "Mary and John and Michael became good friends and are living together",
                "Mary, Rob and Bob are dead"
        };
        String regex = "(?m)^.*\\bMary\\b((?!\\bBob\\b).)*\\bare\\b.*$";
        for(String t : tests) {
            System.out.println(t.matches(regex) + " -> " + t);
        }
    }
}

关于java - 一个正则表达式问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1480570/

相关文章:

jquery - 数据属性中的正则表达式--jquery

python - 在标记自定义迷你格式时正确考虑多个反斜杠

java - 使用 Eclipse 插件 Jigloo 进行 GUI 编程

java - Java正则表达式的初学者问题

Java从类实例中获取表示类的泛型类型

java - commonj.work包中的Work接口(interface)是什么?

javascript - 为什么javascript正则表达式不匹配

javascript - 匹配出现的字符的第一个字符(它们必须彼此相邻)

java - 将日期转换为时间戳

java - <goal>instrument</goal> 中的 JaCoCo(离线检测)分析整个 pom.xml。但我只需要测试部分