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

 幸福欧旭旭_320 发布于 2023-01-11 11:39

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

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

"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);
}

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

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有