How to get text between nested parentheses?

前端 未结 1 2025
甜味超标
甜味超标 2020-11-28 09:40

Reg Expression for Getting Text Between parenthesis ( ), I had tried but i am not getting the RegEx. For this example

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

相关标签:
1条回答
  • 2020-11-28 10:20

    .NET allows recursion in regular expressions. See 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('(', ')'));
    }
    
    0 讨论(0)
提交回复
热议问题