在 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/