.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.