如何在嵌套括号之间获取文本?

时间:2013-10-30 20:54:38

标签: c# regex c#-4.0

获取文本的Reg表达式在括号()之间,我曾尝试过,但我没有得到RegEx。对于这个例子

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

1 个答案:

答案 0 :(得分:33)

.NET允许在正则表达式中使用递归。见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('(', ')'));
}