Replacing each instance of a word in a string with a unique value

Within a string, I'm trying to update multiple instances of the same word with different values.

This is an overly simplified example, but given the following string:

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

The first instance of the word color I want to replace with "red", the second instance should be "green" and the third instance should be "blue".

What I thought to try was a regex pattern to find boundried words, interate through a loop and replace them one at a time. See the example code below.

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

However, the word "color" never gets replaced with the appropriate color name. I can't find what I've been doing wrong.

Answers


Try a match delegate.

It is an overload of Regex.Replace() that most folks miss. It simply lets you define a, potentially context sensitive, dynamic handler instead of a hardcoded string to replace with, and could have side-effects. The "i++ %" is a modulo operator is used below to simply cycle through the values. You could use a database or a hash table or anything.

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

This solution works for an arbitrary number of replacements, which is more typical (global replace).


Need Your Help

Flex Tree does not selecting ("highlight”) the selectedIndices

actionscript-3 flex treeview flex4.5 itemrenderer

I have an array of items that should be selected in my tree control. As you can see from my code below,I bind this array to the selectedIndices property of the tree.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.