【问题标题】:C# Regex - How to remove multiple paired parentheses from stringC# Regex - 如何从字符串中删除多个成对的括号
【发布时间】:2013-01-02 16:31:35
【问题描述】:

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

【问题讨论】:

  • 你能添加你想要的输出吗?
  • 当然。我会更新帖子。
  • 我不认为它是重复的,因为我还询问正常的非嵌套括号和除了嵌套部分之外跨越多行的括号。如果嵌套部分无法完成,我仍然会对其他两个感兴趣。
  • 不成对的括号呢?

标签: c# regex parentheses


【解决方案1】:

幸运的是,.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);

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

如需了解更多信息,请阅读 Jeffrey Friedl 的优秀书籍 "Mastering Regular Expressions"(第 436 页)

【讨论】:

  • @MattBrandon - 在 .NET 中有更简单的方法:Balancing Group Definitions
  • @Cyborgx37:“更简单的方法”是什么意思?我 am 完全使用了您链接到的技术(感谢您的链接 - 我已将其包含在我的答案中)。我只是为计数器使用了不同的名称(Depth 而不是Open),这当然是无关紧要的。
  • 另外,我通常不担心投反对票,但在这种情况下,我很想知道为什么这个答案被某人认为“没有帮助”。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    通常,这不是一个选项。但是,Microsoft 确实对标准正则表达式进行了一些扩展。您可以通过Grouping Constructs 实现此目的,即使将其编码为算法比阅读和理解 Microsoft 对其扩展的解释要快。

    【讨论】:

    • 实际上我今天早些时候通过编写一个算法来解决这个问题。但是,这让我很好奇是否可以使用 Regex 完成
    【解决方案4】:

    这个怎么样: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"
    

    【讨论】:

    • 我认为你最好使用Regex.Escape() 而不是"\\{0}"
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-16
    • 2015-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多