Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Regex - How to remove multiple paired parentheses from string

I am trying to figure out how to use C# regular expressions to remove all instances paired parentheses from a string. The parentheses and all text between them should be removed. The parentheses aren't always on the same line. Also, their might be nested parentheses. An example of the string would be

This is a (string). I would like all of the (parentheses
to be removed). This (is) a string. Nested ((parentheses) should) also
be removed. (Thanks) for your help.

The desired output should be as follows:

This is a . I would like all of the . This  a string. Nested  also
be removed.  for your help.
like image 682
Matt Brandon Avatar asked Jan 18 '13 21:01

Matt Brandon


1 Answers

Fortunately, .NET allows recursion in regexes (see Balancing Group Definitions):

Regex regexObj = new Regex(
    @"\(              # Match an opening parenthesis.
      (?>             # Then either match (possessively):
       [^()]+         #  any characters except parentheses
      |               # or
       \( (?<Depth>)  #  an opening paren (and increase the parens counter)
      |               # or
       \) (?<-Depth>) #  a closing paren (and decrease the parens counter).
      )*              # Repeat as needed.
     (?(Depth)(?!))   # Assert that the parens counter is at zero.
     \)               # Then match a closing parenthesis.",
    RegexOptions.IgnorePatternWhitespace);

In case anyone is wondering: The "parens counter" may never go below zero (<?-Depth> will fail otherwise), so even if the parentheses are "balanced" but aren't correctly matched (like ()))((()), this regex will not be fooled.

For more information, read Jeffrey Friedl's excellent book "Mastering Regular Expressions" (p. 436)

like image 154
Tim Pietzcker Avatar answered Sep 17 '22 16:09

Tim Pietzcker