Oscar Foley
Oscar Foley

Reputation: 7025

Regex to remove all parentheses except most external ones

I have been trying and reading many similar SO answers with no luck. I need to remove parentheses in the text inside parentheses keeping the text. Ideally with 1 regex... or maybe 2?

My text is:

Alpha (Bravo( Charlie))

I want to achieve:

Alpha (Bravo Charlie)

The best I got so far is:

\\(|\\)

but it gets:

Alpha Bravo Charlie

Upvotes: 1

Views: 115

Answers (3)

The fourth bird
The fourth bird

Reputation: 163632

Your pattern \(|\) uses an alternation then will match either an opening or closing parenthesis.

If according to the comments there is only 1 pair of nested parenthesis, you could match:

(\([^()]*)\(([^()]*\)[^()]*)\)
  • ( Start capturing group
  • \( Match opening parenthesis
    • [^()]* Match 0+ times not ( or )
  • ) Close group 1
  • \( Match
  • ( Capturing group 2
    • \([^()]*\) match from ( till )
    • [^()]* Match 0+ times not ( or )
  • ) close capturing group
  • \) Match closing parenthesis

And replace with the first and the second capturing group.

Regex demo

Upvotes: 1

Federico Piazza
Federico Piazza

Reputation: 31035

You can use a regex like this:

(\(.*?)\((.*?)\)

enter image description here

With this replacement string:

$1$2

Regex demo


Update: as per ııı comment, since I don't know your full sample text I provide this regex in case you have this scenario

(\([^)]*)\((.*?)\)

Regex demo

Upvotes: 3

Pushpesh Kumar Rajwanshi
Pushpesh Kumar Rajwanshi

Reputation: 18357

From your post and comments, it seems you want to remove only the inner most parenthesis, for which you can use following regex,

\(([^()]*)\)

And replace with $1 or \1 depending upon your language.

In this regex \( matches a starting parenthesis and \) matches a closing parenthesis and ([^()]*) ensures the captured text doesn't contain either ( or ) which ensures it is the innermost parenthesis and places the captured text in group1, and whole match is replaced by what got captured in group1 text, thus getting rid of the inner most parenthesis and retaining the text inside as it is.

Demo

Upvotes: 1

Related Questions