【问题标题】:How to get text between nested parentheses?如何在嵌套括号之间获取文本?
【发布时间】:2013-11-10 16:44:40
【问题描述】:

用于获取括号 ( ) 之间文本的正则表达式,我已经尝试过,但我没有得到正则表达式。对于这个例子

Regex.Match(script, @"\((.*?)\)").Value

例子:-

add(mul(a,add(b,c)),d) + e - sub(f,g)

Output =>

1) mul(a,add(b,c)),d

2) f,g

【问题讨论】:

  • 如果您需要处理嵌套括号,您应该使用解析器而不是正则表达式。
  • @Lee:嗨.. lee,你能给我举个例子吗?
  • 在这种情况下,您可以在每次匹配时递归地调用该正则表达式,直到没有匹配为止。
  • 你需要使用平衡组,see this awesome answer
  • @sln 他正在尝试匹配“外部”括号中的内容。在 PCRE 中,您可以执行以下操作 \(((?:[^()]|(?R))*)\)

标签: c# regex c#-4.0


【解决方案1】:

.NET 允许在正则表达式中使用 recursion。见Balancing Group Definitions

var input = @"add(mul(a,add(b,c)),d) + e - sub(f,g)";

var regex = new Regex(@"
    \(                    # Match (
    (
        [^()]+            # all chars except ()
        | (?<Level>\()    # or if ( then Level += 1
        | (?<-Level>\))   # or if ) then Level -= 1
    )+                    # Repeat (to go from inside to outside)
    (?(Level)(?!))        # zero-width negative lookahead assertion
    \)                    # Match )",
    RegexOptions.IgnorePatternWhitespace);

foreach (Match c in regex.Matches(input))
{
    Console.WriteLine(c.Value.Trim('(', ')'));
}

【讨论】:

  • 天才!很好的答案!
  • 将其称为递归似乎具有误导性。它只是使用一堆捕获来跟踪嵌套深度。
  • 尝试将您的正则表达式放在此处:regex101.com 它给出了“不完整的组结构”错误。我不知道为什么。有什么想法吗?
  • @jsirr13 regex101.com 目前不支持 .NET 正则表达式引擎。使用 linqpad 或控制台应用程序。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-22
  • 1970-01-01
  • 2010-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多