I have been facing an issue with regular expression string matching. Here is my string - var String detectionString = Stack Overflow (hello)
I tried this regular expression test - \s(detectionString)\b but could succeed to match a string Stack Overflow only. Can anyone help to provide a regular expression string that can match & include words inside parenthesis also.
Here I tried to match my string and successful but it requires regex expression in between string(square bracket covering parenthesis can solve this problem) like (Stack Overflow [ ( ] hello [ ) ]) . and my problem is I can't add expression in between string.
Note: There can be any kind of string with parenthesis like - var String detectionString = Krunal Bhavsar 123 (iOS).
I would suggest quoting the whole target string by enclosing it between
Pattern p = Pattern.compile("\\b\\QStack Overflow (hello)\\E\\b");
That also works very well If you are trying to build patterns dynamically, so that other target strings can be matched. The only caveat in that case is that you need to watch out for the case that the target string contains the two-character substring
\E. If it does, then you'll have escape it.
For example, you might insert
\E\Q between the literal
E. That is, to match the string
This string has literal \E inside you could use
Pattern p = Pattern.compile( "\\b\\QThis string has literal \\\\E\\QE inside\\E\\b");
Note also the distinction between escape syntax for
String literals and escape sequences for interpretation by the regex engine. These are separate layers.
Additionally, I have more or less followed your original pattern attempt with respect to the match boundaries -- that is, by leading and trailing with
\b to match word boundaries. It turns out, however, that the end of the input does not constitute a word boundary for Java's purposes (though the beginning does). Therefore, it may better suit your purpose to use a zero-width assertion in one or both places. For example:
Pattern p = Pattern.compile("(?<!\\w)\\QStack Overflow (hello)\\E(?!\\w)");
Naturally, you may need to tweak the details to your specific needs, but this does work in my tests.