Java模式匹配除给定列表以外的任何字符序列

8

如何编写一个(Java)模式来匹配除了给定单词列表以外的任何字符序列?

我需要查找是否有任何文本被标签包围,例如 除了给定的单词列表中的“one”和“two”之外,我想检查是否有其他单词被标记包围。

"This is the first tag <span>one</span> and this is the third <span>three</span>"

该模式应该匹配上述字符串,因为单词“three”被标签包围,并不是所给单词列表(“one”,“two”)的一部分。

你是否意识到在你编辑之前和之后,你的问题存在如此重要的区别,以至于在你编辑之前回答它的人基本上浪费了他们的时间?下次尝试从一开始就绝对清晰明了。这里没有人有水晶球或可以读懂你的思想。 - Tomalak
3个回答

8

预测搜索可以实现这个功能:

\b(?!your|given|list|of|exclusions)\w+\b

匹配

  • 一个单词边界(单词开头)
  • 不跟随任何“your”,“given”,“list”,“of”,“exclusions”中的任何一个
  • 后面跟着多个字母数字字符
  • 后面跟着一个单词边界(单词结尾)

实际上,这将匹配任何未被排除的单词。


4

这应该能让你开始了解。

import java.util.regex.*;

// >(?!one<|two<)(\w+)/
// 
// Match the character “>” literally «>»
// Assert that it is impossible to match the regex below starting at this position (negative lookahead) «(?!one|two)»
//    Match either the regular expression below (attempting the next alternative only if this one fails) «one»
//       Match the characters “one<” literally «one»
//    Or match regular expression number 2 below (the entire group fails if this one fails to match) «two»
//       Match the characters “two<” literally «two»
// Match the regular expression below and capture its match into backreference number 1 «(\w+)»
//    Match a single character that is a “word character” (letters, digits, etc.) «\w+»
//       Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
// Match the characters “/” literally «</»
List<String> matchList = new ArrayList<String>();
try {
    Pattern regex = Pattern.compile(">(?!one<|two<)(\\w+)/");
    Matcher regexMatcher = regex.matcher(subjectString);
    while (regexMatcher.find()) {
        matchList.add(regexMatcher.group(1));
    } 
} catch (PatternSyntaxException ex) {
    // Syntax error in the regular expression
}

我认为您可能需要将模式中的“one”和“two”更改为“one <”和“two <”,这样您仍然可以匹配以任一字符开头的内容。 - Marty Lamb

2
请使用以下内容:
if (!Pattern.matches(".*(word1|word2|word3).*", "word1")) {
    System.out.println("We're good.");
};

您正在检查模式与字符串匹配。


谢谢你的回复,但这不会起作用。我在问题描述中添加了更多信息。 - Mario

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接