用唯一值替换字符串中单词的每个实例

And*_*ans 6 c# regex

在一个字符串中,我试图用不同的值更新同一个单词的多个实例.

这是一个过于简化的示例,但给出以下字符串:

"The first car I saw was color, the second car was color and the third car was color"
Run Code Online (Sandbox Code Playgroud)

我要用"红色"替换单词颜色的第一个实例,第二个实例应为"绿色",第三个实例应为"蓝色".

我想要尝试的是一个正则表达式模式来查找已结合的单词,通过循环进行交互并一次替换一个.请参阅下面的示例代码.

var colors = new List<string>{ "reg", "green", "blue" };
var sentence = "The first car I saw was color, the second car was color and the third car was color";

foreach(var color in colors)
{
    var regex = new Regex("(\b[color]+\b)");
    sentence = regex.Replace(sentence, color, 1);
}
Run Code Online (Sandbox Code Playgroud)

但是,"颜色"一词永远不会被适当的颜色名称取代.我找不到我做错了什么.

cod*_*eim 4

尝试匹配代表。

大多数人都忽略了 Regex.Replace() 的重载。它只是让您定义一个可能上下文敏感的动态处理程序,而不是要替换的硬编码字符串,并且可能会产生副作用。“i++ %”是一个模运算符,下面使用它来简单地循环遍历值。您可以使用数据库或哈希表或任何东西。

var colors = new List<string> { "red", "green", "blue" };
var sentence = "The first car I saw was color, the second car was color and the third car was color";
int i = 0;
Regex.Replace(sentence, @"\bcolor\b", (m) => { return colors[i++ % colors.Count]; })
Run Code Online (Sandbox Code Playgroud)

该解决方案适用于任意数量的替换,这是更典型的(全局替换)。