【问题标题】:Regular expression, back reference or alternate construct正则表达式、反向引用或替代构造
【发布时间】:2009-11-24 20:49:25
【问题描述】:

我正在尝试在 .NET 中编写一个正则表达式,以从看起来像这样的函数列表中捕获整个函数。

public string Test1()
{
    string result = null;
    foreach(var item in Entity.EntityProperties)
    {
        result +=string.Format("inner string with bracket{0}", "test");
    }
    return result;
}
public string Test5()
{
    return string.Format("inner string with bracket{0}", "test");
}

public string Last()
{
    return string.Format("inner string with bracket{0}", "test");
}

所以我得到了

((?<function>public string (?<fName>\w+)\(\)\s*{.*?})(?=\s*public string))

这将捕获除最后一个函数之外的所有函数...或此

((?<function>public string (?<fName>\w+)\(\)\s*{.*?})(?=\s*(public string)|$))

这将正确匹配除第一个函数之外的所有函数。第一个函数仅部分匹配。

public string Test1()
{
    string result = null;
    foreach(var item in Entity.EntityProperties)
    {
        result +=string.Format("inner string with bracket{0}", "test");
    } <-- the first capture only get to this point.

有什么想法吗?如果可能,请提供一些解释。

【问题讨论】:

  • 你猜怎么着?正则表达式不能很好地处理任意嵌套的大括号。

标签: .net regex recursive-regex


【解决方案1】:

虽然我非常喜欢正则表达式,但在您的情况下,它们将不起作用,因为嵌套结构不是“常规的”,因此无法与正则表达式匹配。你需要一个解析器来完成这种工作。对不起。

【讨论】:

    【解决方案2】:

    实际上可以在 .NET 中检查匹配的括号。关键是使用平衡组。我之前听说过这就是为什么我问这个问题。我只是不确定如何自己编写表达式,所以我希望一些常驻 reg 专家可以帮助我:)

    幸运的是我找到了这个网站。其中详细解释了平衡组……他甚至提供了一个模板。所以这里供大家参考。

    http://blog.stevenlevithan.com/archives/balancing-groups 模式的要点在这里

    {
        (?>
            (?! { | } ) .
        |
            { (?<Depth>)
        |
            } (?<-Depth>)
        )*
        (?(Depth)(?!))
    }
    

    但请查看他的博客了解详细说明。

    【讨论】:

    • 如果您在问题的标题中说明了您想要做的事情,您可能会得到更好的结果。
    • 你说得对,你觉得这样的标题怎么样?我需要一个正则表达式来捕获 c# 源代码中的函数体?
    猜你喜欢
    • 2019-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-01
    相关资源
    最近更新 更多