문제

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

}
도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top