如何编写一个(Java)模式来匹配除了给定单词列表以外的任何字符序列?
我需要查找是否有任何文本被标签包围,例如 除了给定的单词列表中的“one”和“two”之外,我想检查是否有其他单词被标记包围。
"This is the first tag <span>one</span> and this is the third <span>three</span>"
该模式应该匹配上述字符串,因为单词“three”被标签包围,并不是所给单词列表(“one”,“two”)的一部分。
如何编写一个(Java)模式来匹配除了给定单词列表以外的任何字符序列?
我需要查找是否有任何文本被标签包围,例如 除了给定的单词列表中的“one”和“two”之外,我想检查是否有其他单词被标记包围。
"This is the first tag <span>one</span> and this is the third <span>three</span>"
预测搜索可以实现这个功能:
\b(?!your|given|list|of|exclusions)\w+\b
匹配
实际上,这将匹配任何未被排除的单词。
这应该能让你开始了解。
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
}
if (!Pattern.matches(".*(word1|word2|word3).*", "word1")) {
System.out.println("We're good.");
};
您正在检查模式与字符串不匹配。