在字符串中,我正在尝试使用不同的值更新同一个单词的多个实例。
这是一个过于简化的示例,但给出以下字符串:
"The first car I saw was color, the second car was color and the third car was color"
我希望用“red”替换单词color的第一个实例,第二个实例应为“green”,第三个实例应为“blue”。
我想要尝试的是一个正则表达式模式来查找已绑定的单词,通过循环进行交互并逐个替换它们。请参阅下面的示例代码。
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);
}
但是,“颜色”这个词永远不会被适当的颜色名称取代。我找不到我做错了什么。
答案 0 :(得分:3)
尝试匹配委托。
大多数人都错过了Regex.Replace()的重载。它只是让您定义一个潜在的上下文敏感的动态处理程序,而不是要替换的硬编码字符串,并且可能有副作用。 &#34; i ++%&#34;下面使用模数运算符来简单地遍历值。您可以使用数据库或哈希表或任何其他内容。
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]; })
此解决方案适用于任意数量的替换,这是更典型的(全局替换)。
答案 1 :(得分:2)
问题在于,在您的示例中,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);
}
产生这个:
我看到的第一辆车是红色的,第二辆车是绿色的,第三辆是 车是蓝色的
答案 2 :(得分:1)
我尽可能地远离正则表达式。它有它的位置,但不适用于像这样的简单情况恕我直言:)
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));