0

我的代码。

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.
4

6 回答 6

1

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

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);
于 2013-10-01T07:50:33.303 回答
1

没有正则表达式:

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
于 2013-10-01T07:51:02.217 回答
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.

于 2013-10-01T07:41:52.553 回答
0

我已经StrExtractVFP Toolkit for .NET中编辑了函数,并获得了一个我命名为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);
于 2013-10-01T12:23:27.680 回答
0

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

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

于 2013-10-01T07:40:17.723 回答
0

您真的可以使用正则表达式 /((s).*?){n}/ 来搜索第 n 次出现的子字符串 s。

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

sql = sql.Replace("(,", "(").Replace(",)", ")");
于 2013-10-01T07:43:02.137 回答