通过正则表达式模式匹配使用 stringbuilder 替换多次出现的字符串

Replacing mutiple occurrences of string using string builder by regex pattern matching

我们正在尝试用它们各自的 "groups".

替换字符串生成器中的所有匹配模式(正则表达式)

首先,我们试图找到该模式所有出现的次数并循环遍历它们(次数 - 终止条件)。对于每场比赛,我们都会分配比赛对象并使用各自的组替换它们。

此处仅替换第一个匹配项,而不会替换其他匹配项。

      *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'

像这样的正则表达式解决方案太脆弱了。如果你需要解析任意 SQL,你需要一个专用的解析器。在 Parsing SQL code in C#.

中有关于如何正确解析 SQL 的示例

如果您确定输入中没有 "wild"、不平衡的 (),您可以使用正则表达式作为解决方法,对于 one-off工作:

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

参见regex demo

详情

  • ('[^']+') - 捕获第 1 组 (</code>):<code>'' 以外的 1 个或多个字符,然后是 '
  • \s*=\s* - = 包含 0+ 个空格
  • (\w+\((?>[^()]+|(?<o>\()|(?<-o>\)))*\)) - 捕获组 2 (</code>): <ul> <li><code>\w+ - 1+ 个单词字符
  • \((?>[^()]+|(?<o>\()|(?<-o>\)))*\) - 一个 (...) 子串,内部有任意数量的平衡 (...)(参见 )。