.NET正则表达式均衡组EX pression - 匹配时不均衡 [英] .NET Regex balancing groups expression - matching when not balanced

查看:129
本文介绍了.NET正则表达式均衡组EX pression - 匹配时不均衡的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

.NET均衡组的正则表达式让我的脑袋炸开。我有这个字符串我试图匹配:

.NET balanced group regexes make my head explode. I've got this string i'm trying to match:

other stuff blah blah....
                    {
                        stuff stuff
                        {key:
                            stuff
                            stuff
                        }
                    } more stuff.....

下面是我的正则表达式:

Here's my regex:

[^{}]*                      # anything that isn't { }
\{                          # starting with {
(?>                         # atomic group: throw away backtracks on exit
    [^{}]+
  |
    \{(?:\w+:)?(?<DEPTH>)   # on matching { plus optional "word:" push stack  
  |
    \}(?<-DEPTH>)           # on matching } pop stack
)*
(?(DEPTH)(?!))              # if depth unbalanced, fail match
\}                          # ending with }
[^{}]*                      # anything that isn't { }

所以,我试图匹配平衡大括号,有些地方的左大括号有一个可选的字,后跟一个冒号。上述正则表达式匹配我的例子字符串,但如果我删除一个大括号(即不平衡吧):

So, I'm trying to match balancing curly braces, where some of the opening curly braces have an optional word followed by a colon. The above regex matches my example string, but if i remove a curly brace, (i.e. "unbalancing it):

    other stuff blah blah....
                    {
                        stuff stuff
                        {key:
                            stuff
                            stuff

                    } more stuff.....

...它仍然符合!

...it still matches!

谁能告诉我如何解决我的正则表达式?

Can anyone tell me how to fix my regex?

推荐答案

你检查什么是匹配在第二种情况下?既然你没有任何锚,我认为发动机启动的比赛只是第一个{之后。从那里,直到结束,匹配字符串。

Have you checked what it is matching in the second case? Since you don't have any anchors, I think the engine starts the match just after the first '{'. From there, until the end, the string matches.

尝试,围绕着\ A和\ Z模式。

Try surrounding the pattern with \A and \z.

这篇关于.NET正则表达式均衡组EX pression - 匹配时不均衡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆