7

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
  • Instead of a.substring(m.start(), m.end()) you could just write m.group(). Commented Jan 27, 2014 at 19:47

1 Answer 1

14

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.

Sign up to request clarification or add additional context in comments.

2 Comments

No need to be since \b doesn't generate compile time error as \s or \w etc.
He already had the word boundry, just needed to escape the escape for a double quoted string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.