【发布时间】:2023-03-10 01:36:01
【问题描述】:
我们正在尝试用它们各自的“组”替换字符串构建器中的所有匹配模式(正则表达式)。
首先,我们试图找到该模式的所有出现次数并循环遍历它们(计数 - 终止条件)。对于每个匹配,我们都分配匹配对象并使用它们各自的组替换它们。
这里只替换第一个匹配项,从不替换其他匹配项。
*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'
【问题讨论】:
-
请问初始文本是什么?
-
@DmitryBychenko
SELECT DISTINCT 'Fleet'=isnull(rtrim(f.fleet),''), 'cust_clnt_id' = isnull(rtrim(x.cust_clnt_id),'')这是原始字符串。 -
这样的正则表达式解决方案太脆弱了。如果需要解析任意 SQL,则需要专用的解析器。您可以尝试
Regex.Replace(s, @"('[^']+')\s*=\s*(\w+\((?>[^()]+|(?<o>\()|(?<-o>\)))*\))", "\n $2 as $1")(demo),但仍然可能失败。 -
@WiktorStribizew :那个表达对我有用……谢谢。
标签: c# regex replace stringbuilder