16

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
Damian Drygiel
  • 17,900
  • 4
  • 35
  • 28
Thulasiram
  • 8,432
  • 8
  • 46
  • 54
  • 4
    If you need to handle nested parentheses you should use a parser instead of regex. – Lee Oct 30 '13 at 20:57
  • @Lee: Hi.. lee, can you please give me some example? – Thulasiram Oct 30 '13 at 21:00
  • in this case you could recursively keep calling that regex on each match till you have no matches. – Keith Nicholas Oct 30 '13 at 21:01
  • 5
    You need to use balanced groups, [see this awesome answer](http://stackoverflow.com/a/17004406) – HamZa Oct 30 '13 at 21:03
  • Your regex `\((.*?)\)` matches `(mul(a,add(b,c)`, what are you trying to match? –  Oct 30 '13 at 21:06
  • 2
    @sln he's trying to match the stuff from the "outer" brackets. In PCRE, you could do the following [`\(((?:[^()]|(?R))*)\)`](http://regex101.com/r/vI5lO6) – HamZa Oct 30 '13 at 21:09
  • @HamZa : thanks for your answer. i need another help, for RegEx like base on particular function name, if(a>b, param(add(c,d)), param(2)); O/P: param(add(c,d)) and param(2)... – Thulasiram Dec 05 '13 at 09:29
  • @ThulasiRam lolwut. Please try something before asking and reaching for help. Also, why ask me in the comments? Just post a new question since it's a new "challenge". – HamZa Dec 05 '13 at 09:40
  • @HamZa : k... sure. i had posted my question http://stackoverflow.com/questions/20396841/how-to-get-text-with-particular-function-name-and-with-nested-parentheses – Thulasiram Dec 05 '13 at 10:01

1 Answers1

44

.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('(', ')'));
}
Damian Drygiel
  • 17,900
  • 4
  • 35
  • 28