使用 RegEx 平衡匹配括号 [英] Using RegEx to balance match parenthesis

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

问题描述

我正在尝试创建一个 .NET RegEx 表达式,以正确平衡我的括号.我有以下正则表达式:

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)"

应该发生的是 Regex 应该匹配从 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)"

它应该返回这个:

"funcPow((3),2)"

对此的任何帮助将不胜感激.

Any help on this would be appreciated.

推荐答案

正则表达式绝对可以做括号平衡匹配.这可能很棘手,需要一些更高级的 Regex 功能,但并不难.

Regular Expressions can definitely do balanced parentheses matching. It can be tricky, and requires a couple of the more advanced Regex features, but it's not too hard.

示例:

var r = new Regex(@"
    func([a-zA-Z_][a-zA-Z0-9_]*) # The func name

    (                      # First '('
        (?:                 
        [^()]               # Match all non-braces
        |
        (?<open> ( )       # Match '(', and capture into 'open'
        |
        (?<-open> ) )      # Match ')', and delete the 'open' capture
        )+
        (?(open)(?!))       # Fails if 'open' stack isn't empty!

    )                      # Last ')'
", RegexOptions.IgnorePatternWhitespace);

平衡匹配组有几个功能,但在这个例子中,我们只使用捕获删除功能.行 (?<-open> ) ) 将匹配 ) 并删除之前的打开"捕获.

Balanced matching groups have a couple of features, but for this example, we're only using the capture deleting feature. The line (?<-open> ) ) will match a ) and delete the previous "open" capture.

最棘手的一行是(?(open)(?!)),让我解释一下.(?(open) 是一个条件表达式,仅当存在open"捕获时才匹配.(?!) 是一个总是失败的否定表达式.因此,<代码>(?(open)(?!)) 说如果有打开的捕获,则失败".

The trickiest line is (?(open)(?!)), so let me explain it. (?(open) is a conditional expression that only matches if there is an "open" capture. (?!) is a negative expression that always fails. Therefore, (?(open)(?!)) says "if there is an open capture, then fail".

微软的文档也很有帮助.

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

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