正则表达式平衡组
我正在尝试匹配字符串中的平衡大括号 ({})。例如,我想平衡以下几点:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你已经很接近了。
改编自这个问题的第二个答案(我用它作为我的规范“在 C#/.NET 正则表达式引擎中平衡 xxx”答案,如果它对您有帮助,请投票!它过去对我有帮助):
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):