正则表达式平衡组

本文关键字:平衡 正则表达式 | 更新日期: 2023-09-27 18:23:39

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

if (a == 2)
{
  doSomething();
  { 
     int x = 10;
  }
}
// this is a comment
while (a <= b){
  print(a++);
} 

我从MSDN中想出了这个正则表达式,但它运行不好。我想提取{}的多个嵌套匹配集。我只对家长匹配感兴趣

   "[^{}]*" +
   "(" + 
   "((?'Open'{)[^{}]*)+" +
   "((?'Close-Open'})[^{}]*)+" +
   ")*" +
   "(?(Open)(?!))";

正则表达式平衡组

您非常接近。

改编自这个问题的第二个答案(我用它作为我的标准"在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);