mRhNs13
mRhNs13

Reputation: 479

Regex Replace in the string with same value in multiple words

I want to replace the string with the quotes.

Mystring is as like the below:

var query = "SELECT abc.name,abc.owner-name FROM XXX";

I want to replace the string as follows. Expected result

SELECT abc."name",abc."owner-name" FROM XXX

I am using the regex code as follows:

Regex.Replace(query, $@"\b{column.ColumnName}\b", "\"" + column.ColumnName + "\"")

While replacing the following string is obtained the result -

SELECT abc."name",abc."owner-"name"

The name is the separate string and owner-name is the separate string. While trying to replace the name string the other one is getting replaced automatically since the second string contains the word name in it.

Please let me know if there is any solution. Thanks in advance.

Upvotes: 5

Views: 930

Answers (2)

Gopi
Gopi

Reputation: 11

Make sure you are escaping unwanted strings/characters

\b[^-]name\b

Here escapes '-' which is inside [] and matches "name" which is a string

Make use of Regex tester to test the expressions.

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627086

You need to make sure the longer one comes first. You may create a list of the column names, sort by length in the descending order and build an alternation group to form a regex like

\b(?:owner-name|owner|name)\b

See how this regex will work. Note that the alternatives are checked from left to right, and once there is a match, the next alternatives are skipped.

Here is a snippet to handle the items in a dynamic way (see an online C# demo):

var ColumnNames = new List<string> { "owner", "name", "owner-name"};
ColumnNames = ColumnNames.OrderByDescending(x => x.Length).ToList();
var s = "SELECT abc.name,abc.owner-name FROM XXX";
var pattern = $@"\b(?:{string.Join("|", ColumnNames)})\b";
var result = Regex.Replace(s, pattern, "\"$&\"");
Console.WriteLine(result);
// => SELECT abc."name",abc."owner-name" FROM XXX

Upvotes: 4

Related Questions