正则表达式平衡组

发布于 2025-01-02 22:37:48 字数 388 浏览 3 评论 0原文

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

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

// this is a comment

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

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

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

I am trying to match balancing braces ({}) in strings. For example, I want to balance the following:

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

// this is a comment

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

I came up with this regex from MSDN, but it doesn't work well. I want to extract multiple nested matching sets of {}. I am only interested in the parent match

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

南城追梦 2025-01-09 22:37:48

你已经很接近了。

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

You're pretty close.

Adapted from the second answer on this question (I use that as my canonical "balancing xxx in C#/.NET regex engine" answer, upvote it if it helped you! It has helped me in the past):

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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文