正则表达式平衡组

1 c# regex balancing-groups

我试图在字符串中匹配平衡大括号({}).例如,我想平衡以下内容:

if (a == 2)
{
  doSomething();
  { 
     int x = 10;
  }
}

// this is a comment

while (a <= b){
  print(a++);
} 
Run Code Online (Sandbox Code Playgroud)

我从MSDN中得到了这个正则表达式,但是效果不好.我想提取多个{}的嵌套匹配集.我只对父母比赛感兴趣

   "[^{}]*" +
   "(" + 
   "((?'Open'{)[^{}]*)+" +
   "((?'Close-Open'})[^{}]*)+" +
   ")*" +
   "(?(Open)(?!))";
Run Code Online (Sandbox Code Playgroud)

mat*_*fee 5

你很亲密.

改编自这个问题的第二个答案(我使用它作为我的规范"在C#/ .NET正则表达式引擎中平衡xxx"的答案,如果它帮助你就提升它!它曾帮助过我):

var r = new Regex(@"
[^{}]*                  # any non brace stuff.
\{(                     # First '{' + capturing bracket
    (?:                 
    [^{}]               # Match all non-braces
    |
    (?<open> \{ )       # Match '{', and capture into 'open'
    |
    (?<-open> \} )      # Match '}', and delete the 'open' capture
    )+                  # Change to * if you want to allow {}
    (?(open)(?!))       # Fails if 'open' stack isn't empty!
)\}                     # Last '}' + close capturing bracket
"; RegexOptions.IgnoreWhitespace);
Run Code Online (Sandbox Code Playgroud)