没有正则表达式:
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
_“//然后我将删除第一个和最后一个逗号”_这是这部分还是您的下一个问题? –
你真的从中得到了什么结果?乍一看,我不认为你可以用这种方式使用正则表达式(虽然我的知识是有限的) – Nunners
@Tim我提到,因为SQL语法 – Misi