正则表达式跟踪`)`

时间:2013-08-19 12:18:57

标签: .net regex

让我说我的输入是fn(a(b,c),d) fn(a,d) fn(a(b),d)我希望a(b,c),d如何编写一个模式来获取()中的所有内容?第二个fn()很容易第一个和第三个我不知道如何匹配

2 个答案:

答案 0 :(得分:5)

您需要balancing group definitions

result = Regex.Match(subject,
    @"(?<=\()              # Make sure there's a ( before the start of the match
        (?>                # now match...
           [^()]+          # any characters except parens
        |                  # or
           \(  (?<DEPTH>)  # a (, increasing the depth counter
        |                  # or
           \)  (?<-DEPTH>) # a ), decreasing the depth counter
        )*                 # any number of times
        (?(DEPTH)(?!))     # until the depth counter is zero again
      (?=\))               # Make sure there's a ) after the end of the match",
    RegexOptions.IgnorePatternWhitespace).Value;

答案 1 :(得分:2)

你可以分开它

var output=Regex.Split(input,@"(?:\)|^)[^()]*(?:\(|$)");

您将获得输出

a(b,()c),d
a,d
a(b),d