我正在尝试弄清楚如何使用 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/