简体   繁体   English

正则表达式在字符串中替换多个单词中的相同值

[英]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: Mystring如下所示:

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. 名称是单独的字符串,owner-name是单独的字符串。 While trying to replace the name string the other one is getting replaced automatically since the second string contains the word name in it. 在尝试替换名称字符串时,另一个字符串会自动替换,因为第二个字符串中包含单词name。

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 ): 这是一个以动态方式处理项目的片段(请参阅在线C#演示 ):

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

Make sure you are escaping unwanted strings/characters 确保您正在逃避不需要的字符串/字符

\b[^-]name\b

Here escapes '-' which is inside [] and matches " name " which is a string 这里转义'-'[]内部,并匹配“ name ”,这是一个字符串

Make use of Regex tester to test the expressions. 利用Regex测试程序测试表达式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM