C#Regex – 如何从字符串中删除多个配对的括号

我试图弄清楚如何使用C#正则表达式从字符串中删除所有实例配对括号。 应删除括号和它们之间的所有文本。 括号并不总是在同一条线上。 此外,它们可能是嵌套的括号。 字符串的一个例子是

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. 

所需的输出应如下:

 This is a . I would like all of the . This a string. Nested also be removed. for your help. 

幸运的是,.NET允许在正则表达式中递归(请参阅平衡组定义 ):

 Regex regexObj = new Regex( @"\( # Match an opening parenthesis. (?> # Then either match (possessively): [^()]+ # any characters except parentheses | # or \( (?) # 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); 

如果有人想知道:“parens计数器”可能永远不会低于零( 否则会失败),所以即使括号是“平衡的”但没有正确匹配(如()))((() ),这个正则表达式不会被愚弄。

欲了解更多信息,请阅读Jeffrey Friedl的优秀着作“掌握正则表达式” (第436页)

您可以使用空字符串重复替换/\([^\)\(]*\)/g ,直到找不到更多匹配项。

通常,它不是一种选择。 但是,Microsoft确实对标准正则表达式进行了一些扩展。 您可以通过Grouping Constructs实现这一点,即使编写算法编码速度快于阅读和理解Microsoft对其扩展的解释。

怎么样:Regex Replace似乎可以解决问题。

 string Remove(string s, char begin, char end) { Regex regex = new Regex(string.Format("\\{0}.*?\\{1}", begin, end)); return regex.Replace(s, string.Empty); } string s = "Hello (my name) is (brian)" s = Remove(s, '(', ')'); 

输出将是:

 "Hello is"