Java regex not functioning as expected illegal character exception

Viewed 29

I have the following Regex that I built, which works in regex101.com:

(\(.+?\))/g

The regex identifies groups of paren contained text. For example, in the string:

"test item (paren text here) more random content (inside content)"

It matches: (paren text here), and (inside content).

While this combination works in regex101 and even in Javascript, when I have been attempting to use it in Java, I consistently get the error that I am using an illegal escape character. For example, I get that error with the below:

String searchString = "asfdasdf asdfasd asdfasd (adfasdf) asdfasd 
asdfasd AND asdfasdfasd (asfdasd) asfdasdfas";
 
        String pattern = "/(\(.+?\))/g";
        
        Pattern patternFound = Pattern.compile(pattern);
        Matcher matcher = patternFound.matcher(searchString);
        
        System.out.println(matcher.find());

When I use:

String pattern = "/(\\(.+?\\))/g";

I no longer receive the error, but the regex no longer works and returns false.

How can I properly format my regex so that it works in Java the same as it does on regex101 and in JavaScript?

1 Answers
Related