这是我的示例代码:
string pattern = "(@param)(?=.*where)";
string updateQuery = @"update Table set column = @param where otherColumn = @param";
string newUpdateQuery = Regex.Replace(updateQuery, pattern , "CONVERT(NVARCHAR,'param')");
Console.WriteLine(newUpdateQuery);
string insertQuery = @"insert into Table (column) values(@param)";
string newInsertQuery = Regex.Replace(insertQuery, pattern , "CONVERT(NVARCHAR,'param')");
Console.WriteLine(newInsertQuery);
输出:
update Table set column = CONVERT(NVARCHAR,'param') where otherColumn = @param
insert into Table (column) values(@param)
我想在where条件之前匹配参数。
但在插入查询中,该模式不能匹配任何参数。
如果加“?”像这样的模式
string pattern = "(@param)(?=.* where)?"
输出将变成
update Table set column = CONVERT(NVARCHAR,'param') where otherColumn = CONVERT(NVARCHAR,'param')
insert into Table (column) values(CONVERT(NVARCHAR,'param'))
这个输出就是我想要的:
update Table set column = CONVERT(NVARCHAR, 'param') where otherColumn = @param
insert into Table(column) values(CONVERT(NVARCHAR, 'param'))
如果查询有where条件。
只匹配“where”之前的参数
最佳答案
您需要确保只匹配 @param
如果前面没有 where
:
string pattern = @"(?<!\bwhere\b.*)@param";
请参阅C# demo
图案详细信息
-
(?<!\bwhere\b.*)
- 如果存在整个单词where
则匹配失败的负向后查找(\b
是字边界)以及当前位置左侧除换行符之外的任何 0+ 个字符 -
@param
- 文字子字符串(如果需要,在末尾添加\b
以匹配整个单词)。
完整的 C# 测试:
string pattern = @"(?<!\bwhere\b.*)@param";
string updateQuery = @"update Table set column = @param where otherColumn = @param";
string newUpdateQuery = Regex.Replace(updateQuery, pattern , "CONVERT(NVARCHAR,'param')");
Console.WriteLine(newUpdateQuery); // => update Table set column = CONVERT(NVARCHAR,'param') where otherColumn = @param
string insertQuery = @"insert into Table (column) values(@param)";
string newInsertQuery = Regex.Replace(insertQuery, pattern , "CONVERT(NVARCHAR,'param')");
Console.WriteLine(newInsertQuery); // => insert into Table (column) values(CONVERT(NVARCHAR,'param'))
关于c# - 仅当前面没有另一个字符串时才匹配字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45481399/