【问题标题】:How to match strings that contain neither A nor B using Java Regex?如何使用 Java Regex 匹配既不包含 A 也不包含 B 的字符串?
【发布时间】:2013-10-14 15:02:25
【问题描述】:

我是 Java 正则表达式的新手。如果您发现这个问题真的很简单,我深表歉意。但是我已经看到了一些类似的问题并尝试了这些答案,但都没有奏效。

我正在尝试匹配具有模式“括号外的单词(单词)”的字符串,括号内的内容可能有多种选择,但我想排除其中一些。换句话说,应该匹配括号内不包含某些单词的字符串。

例如如果我不希望 A 或 B 在括号内,

 words outside parenthesis ( C )  // should match
 words outside parenthesis ( A )  // should not match
 words outside parenthesis ( B )  // should not match

其中 A 和 B 可以是单词或短语。但它们不会一起出现(模式“AB”不可能出现在括号内)。

我试过了:

    .+\(\s*(?!A|B)\s*\)

和

    .+\(\s*^/(?!A|B)\s*\)

和

    .+\(\s*(?!\bA\b)(?!\bB\b)\s*\)

但是,他们都没有工作。请帮忙!谢谢!

编辑:

也许我没有澄清自己。 A 或 B 可以是单词或短语,这意味着 A 可能是单词 'hello',B 可能是 'hello world',我不希望匹配 'hello' 或 'hello world'。所以 [^AB] 不适用于我的情况,因为那会变成 [^hellohello world]。

【问题讨论】:

  • 可以有嵌套括号吗?
  • (?!A|B) 仅检查某些内容是否未跟随 A 或 B,但不会自动匹配 C。这就是问题所在。
  • @RohitJain,不。不会有嵌套括号。

标签: java regex string


【解决方案1】:

您的正则表达式的问题在于,在执行否定前瞻 (?![^AB]) 之后,您在结束 ) 之前的单词与 \w+ 或 [^)]+ 不匹配

.+\(\s(?!(nomatch|false)\b)\w+\s\)

示例匹配:

words outside parenthesis ( match )  // matches
words outside parenthesis ( true )  // matches

words outside parenthesis ( nomatch )  // doesn't match
words outside parenthesis ( false )  // doesn't match

【讨论】:

  • 太棒了!非常感谢您不仅提供了正确的答案,还指出了我做错了什么。谢谢!!
【解决方案2】:

您可以将此正则表达式模式与Matcher#find() 方法一起使用:

\\([^)]*(?:A|B)[^)]*\\)

如果find() 方法甚至为此模式返回true 一次,那么您的字符串不是有效匹配。

诀窍是找到不应该匹配的模式。如果找到模式,那么您的字符串无效。这更容易实现。

String[] arr = { "words outside parenthesis ( A )", 
                 "words outside parenthesis ( B )",
                 "words outside parenthesis ( C )" 
               };

Pattern pattern = Pattern.compile("\\([^)]*(?:A|B)[^)]*\\)");

for (String str: arr) {
    Matcher matcher = pattern.matcher(str);

    if (matcher.find()) {
        System.out.println(str + " => is not a valid match");
    } else {
        System.out.println(str + " => is a valid match");
    }
}

将A 和B 替换为您需要的单词。如果有更多单词,则将它们附加到交替运算符。

【讨论】:

  • +1 如果不需要捕获 +ve 匹配,这也是一个好方法。
【解决方案3】:

使用这个: String myPattern = "^.*\\([^AaBb]\\)$";

^.* = 可以以任何字符开头,甚至可以不以字符开头。

\\([^AaBb])\\$ = 不以 (A)、(a)、(B) 或 (b) 结尾。

【讨论】:

  • 这行不通,因为 OP 想要否定单词而不是字符。
  • 哦!我不明白。在那种情况下它确实不起作用。
猜你喜欢
  • 1970-01-01
  • 2021-06-02
  • 2010-11-22
  • 1970-01-01
  • 2022-11-19
  • 2013-05-15
  • 2012-01-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多