【问题标题】:C# / Regex - Replacing set of matches with another set of matchesC# / Regex - 用另一组匹配替换一组匹配
【发布时间】:2020-02-14 10:11:58
【问题描述】:

我正在尝试转这个字符串:

INSERT INTO [main].[sqlite_default_schema].[TableName] ([SomeColumn], [SomeOtherColumn], [Last]) VALUES (@param1, @param2, @param3);

进入这个:

INSERT INTO [main].[sqlite_default_schema].[TableName] ([SomeColumn], [SomeOtherColumn], [Last]) 值 (@SomeColumn, @SomeOtherColumn, @Last);

作为正则表达式的初学者,我正在使用这个 C# sn-p:

Regex regex = new Regex(@"\(.*?\)");
MatchCollection matches = regex.Matches(commandText);
if (matches[0].Success && matches[1].Success)
{
    Regex reColNames = new Regex(@"\[\w*\]");
    MatchCollection colNames = reColNames.Matches(matches[0].Value);
    Regex reParamNames = new Regex(@"\@\w*");
    MatchCollection paramNames = reParamNames.Matches(matches[1].Value);
    if (colNames.Count > 0 && colNames.Count == paramNames.Count)
    {
        for (int i = 0; i < paramNames.Count; i++)
        {
            string colName = colNames[i].Value.Substring(1, colNames[i].Length - 2);
            commandText = commandText.Replace(paramNames[i].Value, "@" + colName);
        }
    }
}
return commandText;

这可行,但感觉不对。 有没有办法只使用一个正则表达式来实现相同的结果?

干杯!

【问题讨论】:

  • 这能回答你的问题吗? Regex replace all occurences
  • Imo,该解决方案需要 3 个步骤: 1 -> 在 () 中查找所有内容 2 -> 从 1 中找到的第一组中提取 colNames。 3 -> 根据第二个索引将参数替换为相应的 colNames组。
  • 这样的查询有多少?如果您将单独的查询创建为常量字符串,或者切换到 ORM,会容易得多。
  • 您有一个 CSV 字符串:“@Column1、@Column2、@Column3”。所以使用:string csv = string.Join(",",Enumerable.Range(1,3).Select(x => "@Column" + x.ToString()));
  • @TanveerBadar 这是自动创建语句常量的尝试的一部分。

标签: c# regex


【解决方案1】:

在我看来,您正在用“列”替换所有“参数”文本。为什么不从那开始呢?如果由于您未提及的某些问题而无法做到这一点,请参阅下面的解决方案。

这将批量替换 1 行中的所有内容。

Regex.Replace(query, "param", "column", RegexOptions.None);

【讨论】:

  • 虽然参数是正确的,但我不能确定列名,因为它们实际上代表数据库中表的列。所以 [Column1], [Column2], ... 将是实际名称,例如 [FirstName], [LastName], ...
  • 那么请用更好的例子更新问题。随着模式匹配的进行,目前还不明显。我会把这个答案留给后代。
猜你喜欢
  • 2020-09-01
  • 2014-04-15
  • 2018-09-17
  • 1970-01-01
  • 1970-01-01
  • 2014-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多