Java 模式匹配器问题

Java Pattern Matcher Woes

我正在寻找一种模式来检查布尔项,但仅限于特定条件:


到目前为止,我的代码只有在分隔符前后有空格时才能找到它们,并且任何类型的调整都会破坏我取得的进展。 I used this page 作为参考,但仍然没有骰子。我试过同时使用 find() 和 matches() 但 find 的范围似乎太宽泛,而 matches 似乎不够宽泛。有什么想法吗?

final static Pattern booleanTerms = Pattern.compile("(.*)(( OR )|( or )|( NOT )|( not )( AND )|( and ))(.*)");

public static void main(String[] args) {

Set<String> terms = new HashSet<String>();
terms.add(" OR"); //false
terms.add("or "); //false
terms.add("OR"); // false
terms.add(" or "); //true
for (String s : terms) {
    System.out.println(findDilims(s));
} // end for loop

} // end main method

public static boolean findDilims(String s) {
    Matcher matcher = booleanTerms.matcher(s);
    if (matcher.matches()) {
      return true;
    } else {
      return false;
    }
} // end method

您对“OR”、"or " 和 "OR" 得到 false 的原因是因为您的模式明确地寻找带有 space 的布尔项之前或之后:例如( OR ) 寻找 " OR ".

不需要前后 spaces 来确保每个布尔项都是一个词,您可能想要使用词边界:

Pattern.compile("\b(( OR )|( or )|( NOT )|( not )|( AND )|( and ))\b");

您可以使用 \s* 将可选的白色 space 添加到正则表达式的开头和结尾。这样 " OR \t " 也会匹配。

Pattern.compile("\s*\b(( OR )|( or )|( NOT )|( not )|( AND )|( and ))\b\s*");

matcher.matches() 现在应该可以正常工作了。

你说你只想找到它们本身,而不是作为短语的一部分。那么你不想开始和结束你的模式 (.*).

看来你也想找到他们,即使他们周围都是白色space。然后你需要用 \s* 开始和结束你的模式。即使之前或之后没有 space,你也想找到它们。那么你不想在你的模式中使用 space,例如 ( or )

您似乎希望它不区分大小写,因此您可能希望将其设置为 (?i)

final static Pattern booleanTerms = Pattern.compile("(?i)(\s*)((or)|(not)|(and))(\s*)");

您需要一个字符 class 作为交替项的任意一端:

(?i)(^\s*|[^a-z]\s)(or|not|and)(\s[^a-z]|\s*$)

而你只需要一行:

public static boolean findDilims(String s) {
    return s.matches(".*(?i)(^\s*|[^a-z]\s)(or|not|and)(\s[^a-z]|\s*$).*");
}