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.
Fortunately, .NET allows recursion in regexes (see Balancing Group Definitions):
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)