正規表現なし:
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