【问题标题】:Replace part of a string between the x and x+1 occurrence c#在 x 和 x+1 次出现 c# 之间替换字符串的一部分
【发布时间】:2013-10-01 07:34:55
【问题描述】:

我的代码。

string sql = "INSERT INTO TABLE1(col1, col2, col3, col4, col5) VALUES (, NULL, NULL, NULL, NULL, NULL,)";
//Insert value for the third column(between the 3rd and 4th comma)
Regex rgx = new Regex(@", null"); 
sql = rgx.Replace(sql, ", 'abc'", 3);// this doesn't work
sql = rgx.Replace(sql, ", 'def'", 4);// second insert

想要的结果

sql = "INSERT INTO TABLE1(col1, col2, col3, col4, col5) VALUES (, NULL, NULL, 'abc', 'def', NULL,)";
//Then I'll remove the first and last comma between the VALUES parenthesis.

【问题讨论】:

  • "//那我把第一个和最后一个逗号去掉"这是这一部分还是你的下一个问题?
  • 你实际上从中得到了什么结果?乍一看,我认为您不能以这种方式使用 RegEx(尽管我对它们的了解有限)
  • @Tim 我提到了因为 SQL 语法

标签: c# string replace find-occurrences


【解决方案1】:

这样使用;

string sql = "INSERT INTO TABLE1(col1, col2, col3, col4, col5) VALUES (,NULL, NULL, NULL, NULL, NULL,)";

string nulls = "NULL";
List<int> indexes = new List<int>();
foreach (Match match in Regex.Matches(sql, nulls))
{
     indexes.Add(match.Index);
}

sql = sql.Remove(indexes[2], 4).Insert(indexes[2], "'abc'");
Console.WriteLine(sql);

输出将是;

INSERT INTO TABLE1(col1, col2, col3, col4, col5) VALUES (,NULL, NULL, 'abc', NULL
, NULL,)

作为解释,这将在您的查询中找到第三个NULL,然后将其自身替换为'abc'

这里是 DEMO

【讨论】:

  • 很好的例子,但是......当我想进行第二次插入时会发生什么?第一次插入后,索引列表不再对应。
  • @Misi 您可以在sql = sql.Remove(indexes[2], 4).Insert(indexes[2], "'abc'"); 行中更改索引但请记住,当您插入第一个'abc' 时,索引可从03,因为您有4 个NULL 而不是5 个你的 sql。
【解决方案2】:

您可以使用此扩展方法。 this的修改版。

public static string ReplaceSpecifiedIndex(this string input, string valueToBeReplaced, string replacingvalue, int index)
  {
            input = input.ToLower();
            valueToBeReplaced = valueToBeReplaced.ToLower();
            replacingvalue = replacingvalue.ToLower();
            Match m = Regex.Match(input, "((" + valueToBeReplaced + ").*?){" + index + "}");
            int specificIndex = -1;
            if (m.Success)
                specificIndex = m.Groups[2].Captures[index - 1].Index;

     if (specificIndex > -1)
     {
                string temp = input.Substring(specificIndex, valueToBeReplaced.Length);
                int nextsubstring = specificIndex + valueToBeReplaced.Length;
                input = input.Substring(0, specificIndex) + temp.Replace(valueToBeReplaced, replacingvalue) + input.Substring(nextsubstring);
      }
      return input;
  }

然后这样称呼它

string sql = "INSERT INTO TABLE1(col1, col2, col3, col4, col5) VALUES (, NULL, NULL, NULL, NULL, NULL,)";
sql = sql.ReplaceSpecifiedIndex("null", "abc", 3);

【讨论】:

    【解决方案3】:

    没有正则表达式:

    string sql = "INSERT INTO TABLE1(col1, col2, col3, col4, col5) VALUES (, NULL, NULL, NULL, NULL, NULL,)";
    int indexOfvalues = sql.IndexOf("VALUES (");
    if (indexOfvalues >= 0)
    {
        indexOfvalues += "VALUES (".Length;
        int endIndexOfvalues = sql.IndexOf(")", indexOfvalues);
        if (endIndexOfvalues >= 0)
        {
            string sqlValues = sql.Substring(indexOfvalues, endIndexOfvalues - indexOfvalues);
            string[] values = sqlValues.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            if(values.Length >= 3)
                values[2] = "'abc'";
            string newValues = string.Join(",", values);
            sql = string.Format("{0}{1})", sql.Substring(0, indexOfvalues), newValues.Trim());
        }
    }
    

    结果:

    INSERT INTO TABLE1(col1, col2, col3, col4, col5) VALUES (NULL, NULL, 'abc', NULL, NULL)
    

    或者用String.Split 更短更易读(可能更危险一点):

    string sql = "INSERT INTO TABLE1(col1, col2, col3, col4, col5) VALUES (, NULL, NULL, NULL, NULL, NULL,)";
    string[] tokens = sql.Split(new[] { "VALUES" }, StringSplitOptions.None);
    if (tokens.Length == 2)
    {
        string[] values = tokens[1].Trim('(', ')', ',', ' ').Split(',');
        if (values.Length >= 3)
            values[2] = "'abc'";
        string newValues = string.Join(",", values);
        sql = string.Format("{0} VALUES ({1})", tokens[0], newValues);
    }
    
    // same result
    

    【讨论】:

      【解决方案4】:

      MatchEvaluator 只是一个委托。你传入你的函数。

      https://stackoverflow.com/a/4566891/431471

      【讨论】:

        【解决方案5】:

        You really could use the regular expression /((s).*?){n}/ to search for n-th occurrence of substring s.

        关于//Then I'll remove the first and last comma.

        sql = sql.Replace("(,", "(").Replace(",)", ")");
        

        【讨论】:

          【解决方案6】:

          我从VFP Toolkit for .NET 编辑了StrExtract 函数,并获得了一个我命名为StrReplace 的新函数。

          public static string StrReplace(string cSearchExpression, string replacement, string cBeginDelim, string cEndDelim, int nBeginOccurence)
              {
                  string cstring = cSearchExpression;
                  string cb = cBeginDelim;
                  string ce = cEndDelim;
          
                  if (cSearchExpression.Contains(cBeginDelim) == false && cSearchExpression.Contains(cEndDelim) == false)
                  {
                      return cstring;
                  }
          
                  //Lookup the position in the string
                  int nbpos = At(cb, cstring, nBeginOccurence) + cb.Length - 1;
                  int nepos = cstring.IndexOf(ce, nbpos + 1);
          
                  //Reaplce the part of the string if we get it right
                  if (nepos > nbpos)
                  {
                      cstring = cstring.Remove(nbpos, nepos - nbpos).Insert(nbpos, replacement);
                  }
                  return cstring;
              }
          

          At函数可以在工具包中找到。

          sql = strings.StrReplace(sql , " abc", ",", ",", 3);
          sql = strings.StrReplace(sql , " def", ",", ",", 4);
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2022-10-07
            • 2021-01-01
            • 1970-01-01
            • 2021-02-09
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多