Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get text between nested parentheses?

Tags:

c#

regex

c#-4.0

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

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

Example:-

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

Output =>

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

2) f,g
like image 635
Thulasiram Avatar asked Oct 30 '13 20:10

Thulasiram


1 Answers

.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('(', ')'));
}
like image 181
Damian Drygiel Avatar answered Oct 25 '22 20:10

Damian Drygiel