Java Regex Word Boundaries

醉酒当歌 提交于 2019-12-19 18:15:08

问题


Hi I have the following code which is meant to find the word "is" but not when it is within another string so the word "this" should not return a match so I use \b. But the following code does not find a match and I cant figure out why?

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()));
    }

}

回答1:


Double escape it:

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

Regex in Java requires you to doubly escape certain special regex symbols, one escaping for Java and another for underlying regex engine.



来源:https://stackoverflow.com/questions/21389837/java-regex-word-boundaries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!