在一个字符串中,我试图用不同的值更新同一个单词的多个实例.
这是一个过于简化的示例,但给出以下字符串:
"The first car I saw was color, the second car was color and the third car was color"
我要用"红色"替换单词颜色的第一个实例,第二个实例应为"绿色",第三个实例应为"蓝色".
我想要尝试的是一个正则表达式模式来查找已结合的单词,通过循环进行交互并一次替换一个.请参阅下面的示例代码.
var colors = new List{ "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); }
但是,"颜色"一词永远不会被适当的颜色名称取代.我找不到我做错了什么.