c# - 正则表达式平衡组

标签 c# regex balancing-groups

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

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

// this is a comment

while (a <= b){
  print(a++);
} 

我从 MSDN 想出了这个正则表达式,但效果不佳。我想提取 {} 的多个嵌套匹配集。我只对父匹配感兴趣

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

最佳答案

你很接近。

改编自 this question 上的第二个答案(我将其用作我的规范“在 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);

关于c# - 正则表达式平衡组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9155483/

相关文章:

c# - 具有平衡组的正则表达式

正则锻炼: factorials

javascript - 从JS中的字符串中提取姓名和电子邮件

python - 如何在 Python 中使用 re 替换两个数字之间的字符?

c# - 为什么 C# 包含不符合 CLS 的编程结构?

c# - 从自定义 header 中检索访问 token

regex - 为不使用惰性重复量词编写更好的正则表达式

c# - 如何进行平衡组捕获?

c# - GraphQL .NET Core Visual Studio 2019 错误建议

c# - VSTO WPF 模式对话框光标在文本框中不闪烁