Yich Lin
Yich Lin

Reputation: 435

Match string only if not preceded with another

Here is my sample code:

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);

output:

update Table set column = CONVERT(NVARCHAR,'param') where otherColumn = @param  
insert into Table (column) values(@param)  

I want match parameter before where condition.
But in insert query,this pattern cannot match any parameter.
If add '?' in pattern like this

string pattern = "(@param)(?=.* where)?"

output will become

update Table set column = CONVERT(NVARCHAR,'param') where otherColumn = CONVERT(NVARCHAR,'param')
insert into Table (column) values(CONVERT(NVARCHAR,'param'))

This output is what I want:

update Table set column = CONVERT(NVARCHAR, 'param') where otherColumn = @param
insert into Table(column) values(CONVERT(NVARCHAR, 'param'))

If a query have where condition.
Only match param before "where"

Upvotes: 2

Views: 156

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626861

You need to make sure you only match @param if it is not preceded with where:

string pattern = @"(?<!\bwhere\b.*)@param";

See the C# demo

Pattern details

  • (?<!\bwhere\b.*) - a negative lookbehind that fails the match if there is a whole word where (\b are word boundaries) and again any 0+ chars other than a newline immediately to the left of the current position
  • @param - a literal substring (add \b at the end to match as a whole word if needed).

Full C# test:

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'))

Upvotes: 4

Related Questions