Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex Replace in the string with same value in multiple words

Tags:

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.

like image 895
mRhNs13 Avatar asked Jul 26 '18 08:07

mRhNs13


1 Answers

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
like image 94
Wiktor Stribiżew Avatar answered Oct 11 '22 17:10

Wiktor Stribiżew