Search code examples
javaregexreplaceall

How to replace a substring within double parentheses in Java?


I need to replace a substring within double parentheses with an empty one. I use:
source = source.replaceAll("\(.+?\)", "");

The substrings within single parentheses are removed. Instead, when I try with a substring within double parentheses the entire substring is removed but the last ')' remains.
What's wrong here?

Thanks in advance.


Solution

  • The +? means that your match is going to take the least amount of characters possible, meaning that it will grab the inner parenthesized statement.

    Try:

    source = source.replaceAll("\(?\(.+?\)\)?", "");
    

    I've just wrapped your regex with \(? and \)?.