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# - 为什么 Guid.ToString ("n") 与从同一 guid 的字节数组生成的十六进制字符串不同?

c# - 使用opencv捕获视频

javascript - 如何访问匹配的 RegExp 特殊表达式?

regex - 匹配方括号 url 标签的正则表达式

regex - 正则表达式:数值范围

c# - 指令重新排序

c# - 使用数据属性使 web api 以键值作为键序列化字典

c# - 大括号 c# 拆分问题

regex - git-svn clone 忽略文件夹的路径正则表达式

Java 正则表达式或 XML 解析器?