Mat*_*don 12 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.
Run Code Online (Sandbox Code Playgroud)
所需的输出应如下:
This is a . I would like all of the . This a string. Nested also
be removed. for your help.
Run Code Online (Sandbox Code Playgroud)
Tim*_*ker 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);
Run Code Online (Sandbox Code Playgroud)
如果有人想知道:"parens计数器"可能永远不会低于零(<?-Depth>否则会失败),所以即使括号是"平衡的"但没有正确匹配(如()))((()),这个正则表达式也不会被愚弄.
欲了解更多信息,请阅读Jeffrey Friedl的优秀着作"掌握正则表达式"(第436页)
| 归档时间: |
|
| 查看次数: |
5470 次 |
| 最近记录: |