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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With