繁体   English   中英

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

[英]C# Regex - How to remove multiple paired parentheses from string

我试图弄清楚如何使用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
       \( (?<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计数器”可能永远不会低于零( <?-Depth>否则会失败),所以即使括号是“平衡的”但没有正确匹配(如()))((() ),这个正则表达式不会被愚弄。

欲了解更多信息,请阅读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"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM