通过正则表达式模式匹配使用字符串生成器替换字符串的多个出现

时间:2019-07-02 07:03:39

标签: c# regex replace stringbuilder

我们正在尝试将字符串生成器中的所有匹配模式(正则表达式)替换为其各自的“组”。

首先,我们尝试查找该模式所有出现的次数并循环遍历(计数-终止条件)。对于每个匹配项,我们都分配匹配项,并使用各自的组替换它们。

这里只有第一个匹配项被替换,而其他匹配项则永远不会被替换。

      *str* - contains the actual string

      Regex - ('.*')\s*=\s*(.*)

要匹配模式:

    'nam_cd'=isnull(rtrim(x.nam_cd),''), 
    'Company'=isnull(rtrim(a.co_name),'')

模式:使用https://regex101.com/

创建
*matches.Count* - gives the correct count (here 2)


String pattern = @"('.*')\s*=\s*(.*)";
MatchCollection matches = Regex.Matches(str, pattern);
StringBuilder sb = new StringBuilder(str);
Match match = Regex.Match(str, pattern);

for (int i = 0; i < matches.Count; i++)
{
    String First = String.Empty;
    Console.WriteLine(match.Groups[0].Value);
    Console.WriteLine(match.Groups[1].Value);

    First = match.Groups[2].Value.TrimEnd('\r');
    First = First.Trim();
    First = First.TrimEnd(',');

    Console.WriteLine(First);

    sb.Replace(match.Groups[0].Value, First + " as " + match.Groups[1].Value) + " ,", match.Index, match.Groups[0].Value.Length);
    match = match.NextMatch();
}

当前输出:

SELECT DISTINCT
         isnull(rtrim(f.fleet),'') as 'Fleet' ,
        'cust_clnt_id' = isnull(rtrim(x.cust_clnt_id),'')

预期输出:

SELECT DISTINCT
 isnull(rtrim(f.fleet),'') as 'Fleet' ,
 isnull(rtrim(x.cust_clnt_id),'') as 'cust_clnt_id'

1 个答案:

答案 0 :(得分:0)

像这样的正则表达式解决方案太脆弱了。如果您需要解析任意SQL,则需要一个专用的解析器。在Parsing SQL code in C#中有一些有关如何正确解析SQL的示例。

如果您确定输入中没有“野生”,无歧义的(),则可以使用正则表达式作为一项一次性工作的解决方法:

var result = Regex.Replace(s, @"('[^']+')\s*=\s*(\w+\((?>[^()]+|(?<o>\()|(?<-o>\)))*\))", "\n $2 as $1");

请参见regex demo

详细信息

  • ('[^']+')-捕获组1($1):',除了'之外还有1个或更多字符,然后是'
  • \s*=\s*-=内含0+空格
  • (\w+\((?>[^()]+|(?<o>\()|(?<-o>\)))*\))-捕获组2($2):
    • \w+-1个以上的字符字符
    • \((?>[^()]+|(?<o>\()|(?<-o>\)))*\)-一个(...)子字符串,内部包含任意数量的平衡(...)(请参阅my explanation of this pattern)。