word boundary and pattern quote not working

1.4k views Asked by At
String haystack = "hey (( howdy";
haystack.matches(".*\\b\\Q((\\E\\b.*");

Line 2 should return true, but it returns false. Is this bug in Java, or am I doing it wrong?

Edit : What I am trying to achieve is see if an user input (complete word) is present in the haystack

2

There are 2 answers

8
Jorge Campos On

To do what you want you just need to search for the user input.

public static void main(String[] args) {
    String test = "some text (( other text inside a stack";
    String userInput = "((";

    Pattern p = Pattern.compile(".*" + Pattern.quote(userInput) + ".*");
    Matcher m = p.matcher(test);
    System.out.println(m.find());
}

The problem is that (( is not a word, therefore it can't be matched when preceded and suffixed by \b

It prints:

true

Note: To fit in a program that can matches both. You will probably test first if the user input is a word if yes you use boundaries if not this above solution.

0
Tobias Roloff On

Most likely it has something to do with the '\b' Word Boundary matching as it is implementation dependant according to this article: http://www.regular-expressions.info/wordboundaries.html

Have you tried:

String haystack = "hey (( howdy";
haystack.matches(".*\\b \\Q((\\E \\b.*"));

Note the spaces before/after \b.