3

在以下 Java 代码中:

public static void main(String[] args) {
        String largeText = "abc myphrase. def";
        String phrase = "myphrase.";
        Pattern myPattern = Pattern.compile("\\b"+Pattern.quote(phrase)+"\\b");
        System.out.println("Pattern: "+myPattern);
        Matcher myMatcher = myPattern.matcher( largeText );
        boolean found = false;
        while(myMatcher.find()) {
          System.out.println("Found: "+myMatcher.group());
          found = true;
        }
        if(!found){
            System.out.println("Not found!");
        }
}

我得到这个输出:

Pattern: \b\Qmyphrase.\E\b
Not found!

拜托,有人能解释一下为什么上面的模式不匹配吗?如果我使用“myphrase”而不是“myphrase”,我确实有一个匹配项。在模式中。

谢谢您的帮助。

4

3 回答 3

4

. 在单词字符和非单词字符之间出现 A 边界后没有边界。由于." "(space) 都是非单词字符,因此它们之间没有界限。

如果你在你的模式中使用“myphase”,你会得到一个匹配,因为单词 charactere..

于 2012-06-01T00:15:41.053 回答
1

它不匹配,因为点 ( .)被视为“单词”字符,因此在文字点之后不会有单词边界(当下一个字符是空格时)。

仅供参考,“单词”字符(有自己的 regex \w)相当于字符类[a-zA-Z0-9_]

于 2012-06-01T00:17:00.720 回答
0

也许您正在尝试使用 \s 而不是 \b ?

于 2012-06-01T02:17:20.480 回答