0

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?

3
  • 1
    It might make sense to include the exact escaped version you've tried, since escaping is mandatory. Commented Sep 12, 2022 at 19:50
  • If you use Eclipse, you can use marketplace.eclipse.org/content/quickrex for a more Java centric Regexp. Commented Sep 12, 2022 at 19:52
  • 2
    It should be: String pattern = "(\\(.+?\\))"; as there are no regex delimiters in Java. Commented Sep 12, 2022 at 19:54

1 Answer 1

2

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.

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

Comments

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.