使用正则表达式来平衡匹配括号 [英] Using RegEx to balance match parenthesis

查看:203
本文介绍了使用正则表达式来平衡匹配括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个.NET正则表达式EX pression,将适当地平衡了我的括号。我有以下的正则表达式EX pression:

I am trying to create a .NET RegEx expression that will properly balance out my parenthesis. I have the following RegEx expression:

func([a-zA-Z_][a-zA-Z0-9_]*)\(.*\)

我想匹配的字符串是这样的:

The string I am trying to match is this:

"test -> funcPow((3),2) * (9+1)"

会发生什么情况是正则表达式应该匹配一切从 funcPow 直到第二个右括号。第二右括号后应该停止。相反,它是一路匹配到最后的右括号。正则表达式是返回这样的:

What should happen is Regex should match everything from funcPow until the second closing parenthesis. It should stop after the second closing parenthesis. Instead, it is matching all the way to the very last closing parenthesis. RegEx is returning this:

"funcPow((3),2) * (9+1)"

这应该返回这样的:

It should return this:

"funcPow((3),2)"

在这个任何帮助将是AP preciated。

Any help on this would be appreciated.

推荐答案

使用平衡的群体,那就是:

Using balanced groups, it is:

Regex rx = new Regex(@"func([a-zA-Z_][a-zA-Z0-9_]*)\(((?<BR>\()|(?<-BR>\))|[^()]*)+\)");

var match = rx.Match("funcPow((3),2) * (9+1)");

var str = match.Value; // funcPow((3),2)

(?&LT; BR&GT; \()|(小于 - BR&GT; \))

是的均衡组(即 BR 我使用的名称是括号)。它以这种方式更清晰<$c$c>(?<BR>\(<$c$c>)|(?<-BR>\)<$c$c>)或许,这样的 \( \)更明显。

(?<BR>\()|(?<-BR>\)) are a Balancing Group (the BR I used for the name is for Brackets). It's more clear in this way (?<BR>\()|(?<-BR>\)) perhaps, so that the \( and \) are more "evident".

如果你真的恨自己(和世界/你的同胞共同的程序员)就够用了这些东西,我建议使用 RegexOptions.IgnorePatternWhitespace 和洒白空间无处不在: - )

If you really hate yourself (and the world/your fellow co-programmers) enough to use these things, I suggest using the RegexOptions.IgnorePatternWhitespace and "sprinkling" white space everywhere :-)

这篇关于使用正则表达式来平衡匹配括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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