使用C#/类Regex进行多行搜索和替换

问题描述

| 我有一些包含以下内容的存储过程:
SELECT columnA,columnB,COUNT(*) AS \"COUNT\" INTO temporaryTable
FROM tableA
WHERE columnA = \"A\"
  AND ISNULL(columnB,\"B\") = \"B\"
GROUP BY columnA,columnB
HAVING columnA = \"A\"
  AND ISNULL(columnB,\"B\") = \"B\"
SELECT * FROM temporaryTable -- There is not necessary to have an empty line between two instructions.
如前所述,有一些过程,所以同一脚本中有很多指令。 我将这些过程中的每个过程都加载到StringBuilder中(它包含与上面显示的脚本相同的脚本)。 我想删除HAVING部分,如果只有(
IF
!)。它与WHERE部分完全相同(如上所述)。 因此,我立即想到了正则表达式。 我有这样的东西:
    static string RemoveHaving(Match m)
    {
        if (m.Groups[3].Value == m.Groups[7].Value)
        { /* WHERE == HAVING */
            Console.WriteLine(\"Same\");
            return string.Concat(m.Groups[1].Value,m.Groups[9].Value);
        }

        Console.WriteLine(\"Not Same\");
        return m.Groups[0].Value;
    }

    static void Main(string[] args)
    {
        // For the example:
        StringBuilder procedure = new StringBuilder();
        procedure.Append(@\"
            SELECT columnA,COUNT(*) AS \"COUNT\" INTO temporaryTable
            FROM tableA
            WHERE columnA = \"A\"
              AND ISNULL(columnB,\"B\") = \"B\"
            GROUP BY columnA,columnB
            HAVING columnA = \"A\"
              AND ISNULL(columnB,\"B\") = \"B\"
            SELECT * FROM temporaryTable -- There is not necessary to have an empty line between two instructions.\");

        Regex reg = new Regex(@\"((.*)where(.*)([\\s^]+)group\\s*by(.*)([\\s^]+))having(.*)([\\s^]+(SELECT|INSERT|UPDATE|DELETE))\",RegexOptions.Compiled |
            RegexOptions.IgnoreCase |
            RegexOptions.Multiline);

        string newProcedure = reg.Replace(procedure,(MatchEvaluator)RemoveHaving);
        Console.WriteLine(\"---\");
        Console.WriteLine(newProcedure);
        Console.WriteLine(\"---\");
    }
它有效,但似乎不是最好的方法... 如何安全检测HAVING的结束? 您将如何管理这项工作?     

解决方法

首先想到的是:
string pattern = @\"WHERE\\s+([\\s\\S]*?)\\s+HAVING\\s+\\1\\s+(SELECT|$)\";
string output = Regex.Replace(input,pattern,@\"WHERE $1 SELECT\");
但是,这仅在语句后紧跟SELECT关键字或行尾的情况下有效。条件子句中对空格的不同使用也会使它失去作用,子句的重新排序也一样。如果您想要以一种健壮的方式执行此操作,那么如果没有某种专门的SQL解析器/优化器,它将变得非常复杂。