12

我试图弄清楚如何使用 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.
4

4 回答 4

22

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

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);

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

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

于 2013-01-18T21:26:31.923 回答
2

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

于 2013-01-18T21:26:38.963 回答
1

通常,这不是一种选择。但是,Microsoft 确实对标准正则表达式进行了一些扩展。即使将算法编码为算法比阅读和理解 Microsoft 对其扩展的解释更快,您也可以使用Grouping Constructs来实现这一点。

于 2013-01-18T21:30:38.410 回答
0

这个怎么样: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"
于 2013-01-18T21:28:29.643 回答