Home > Software design >  Java regex not functioning as expected illegal character exception
Java regex not functioning as expected illegal character exception

Time:09-13

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?

CodePudding user response:

You problem is that Java don't use the // delimiter: you muse use "(\\(. ?\\))".

The syntax differs from JavaScript because there is actually a sugar syntax for pattern: /azerty/g is same as new RegEx("azerty", "g"):

In Java, we only have Pattern.compile and flags are represented by ints.

  • Related