Java 正则表达式中的单词边界

7

您好,我有下面这段代码,用于查找单词“is”,但不包括它作为其他字符串的一部分的情况,因此单词“this”不应匹配,所以我使用\b。但是下面的代码没有找到匹配项,我无法弄清原因。

public static void main(String[] args) {
    String a = "This island is beautiful.";
    Pattern p = Pattern.compile("\bis\b");
    Matcher m = p.matcher(a);

    while(m.find()){

        System.out.println(a.substring(m.start(), m.end()));
    }

}

你可以使用 m.group() 代替 a.substring(m.start(), m.end()) - Keppil
1个回答

14

双重转义:

Pattern p = Pattern.compile("\\bis\\b");

在Java中使用正则表达式需要对某些特殊的正则表达式符号进行双重转义,一次是针对Java本身的转义,另一次是为了底层的正则表达式引擎。


不需要像\s\w等一样,因为\b不会产生编译时错误。 - anubhava
他已经有了单词 "boundry",只需要对双引号字符串进行转义即可。 - user557597

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