没有正则表达式:
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