使用正则表达式来平衡匹配括号括号、正则表达式

2023-09-02 21:08:05 作者:゛恪·守??

我想创建一个.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 我使用的名称是括号)。它以这种方式更清晰(?<BR>()|(?<-BR>))或许,这样的更明显。

(?<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 :-)