Antonio F.
Antonio F.

Reputation: 431

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.

Upvotes: 0

Views: 605

Answers (2)

Dave
Dave

Reputation: 11899

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 \)?.

Upvotes: 1

user180100
user180100

Reputation:

source.replaceAll("\(\([^\(]*\)\)", ""); ?

(not tested)

Upvotes: 1

Related Questions