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

本文关键字:单词 实例 字符串 唯一 替换 | 更新日期: 2023-09-27 18:07:20

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

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

"The first car I saw was color, the second car was color and the third car was color"

我想用"红色"替换单词color的第一个实例,第二个实例应该是"绿色",第三个实例应该是"蓝色"。

我想尝试的是一个regex模式来找到有边界的单词,通过循环进行交互,并一次替换一个。参见下面的示例代码。

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

然而,单词"color"永远不会被适当的颜色名称所取代。我找不到我做错了什么。

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

尝试匹配委托。

这是大多数人忽略的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]; })

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

问题在于,在您的示例中,color的前后并不总是后跟一个非单词字符。对于您的示例,这对我有效:

var regex = new Regex("'b?(color)'b?");

:

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";
foreach(var color in colors)
{
    var regex = new Regex("'b?(color)'b?");
    sentence = regex.Replace(sentence, color, 1);
}

生产:

我看到的第一辆车是红色的,第二辆车是绿色的,第三辆车是蓝色的

我尽量避免使用正则表达式。它有它的地方,但不是像这样的简单情况IMHO:)

public static class StringHelpers
{
    //Copied from http://stackoverflow.com/questions/141045/how-do-i-replace-the-first-instance-of-a-string-in-net/141076#141076
    public static string ReplaceFirst(this string text, string search, string replace)
    {
        int pos = text.IndexOf(search);
        if (pos < 0)
        {
            return text;
        }
        return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
    }
}

var colors = new List<string>{ "red", "green", "blue" };
string sentence = colors.Aggregate(
    seed: "The first car I saw was color, the second car was color and the third car was color", 
    func: (agg, color) => agg.ReplaceFirst("color", color));