c# - 仅当前面没有另一个字符串时才匹配字符串

标签 c# regex

这是我的示例代码:

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/

相关文章:

c# - 如何从类中返回错误

c# - C#中的Unicode字符串

c# - 正则表达式在 C# 中不匹配

JavaScript 正则表达式 : What am I replacing?

c# - 匿名委托(delegate)作为函数参数

c# - 如何使用 CHARACTER * 50 类型的参数将参数从 C# 传递到 FORTRAN?

c# - 如何在表格单元格中创建斜线

使用搜索语法解析搜索词的正则表达式模式

javascript - 限制表单字段中的字符

Java 和 Javascript 正则表达式