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

标签 c# regex parentheses

我正在尝试弄清楚如何使用 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 允许在正则表达式中递归(参见 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);

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

有关更多信息,请阅读 Jeffrey Friedl 的优秀著作 "Mastering Regular Expressions" (第 436 页)

关于C# Regex - 如何从字符串中删除多个成对的括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14407821/

相关文章:

java - 有人知道为什么 String.matches(regex) 不能处理 ANSI 颜色字符串吗?

python - 尝试删除 python 文本中的括号时出错

java - 当第一个字符与任何其他字符一起使用时,正则表达式出错

emacs:当光标突出显示括号时评估闪烁匹配打开

javascript - 突出显示输入框内的括号

c# - 从 C# 调用 Delphi DLL 函数

c# - 绑定(bind)到对象的属性

c# - Visual Studio 2010 长时间调试

Lua:用括号括起来时类变量的 bool 转换的解决方法

c# - 我应该在 Entity Framework 中使用继承还是有更好的方法?