Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex replace - how to replace same pattern in multiple places with different strings?

Tags:

c#

regex

I have a peculiar problem..!

I have a string with some constant value at multiple paces. For example consider the following sting.

string tmpStr = "Hello _tmp_ how is _tmp_ this possible _tmp_ in C#...?"

Now i want to replace each of the tmp in the string with values that are stored in an array, first tmp holds array[0], second tmp holds array[1] and so on...

Any idea how this can be achieved..? I use C# 2.0

like image 414
Amit Avatar asked Jan 18 '10 05:01

Amit


4 Answers

How about this:

string input = "Hello _tmp_ how is _tmp_ this possible _tmp_ in C#...?";
string[] array = { "value1", "value2", "value3" };

Regex rx = new Regex(@"\b_tmp_\b");

if (rx.Matches(input).Count <= array.Length)
{
    int index = 0;
    string result = rx.Replace(input, m => array[index++]);
    Console.WriteLine(result);
}

You need to ensure the number of matches found is never greater than the array's length, as demonstrated above.

EDIT: in response to the comment, this can easily work with C# 2.0 by replacing the lambda with this:

string result = rx.Replace(input, delegate(Match m) { return array[index++]; });
like image 93
Ahmad Mageed Avatar answered Oct 04 '22 22:10

Ahmad Mageed


you can use a MatchEvaluator (a function that gets called to do do each replacement), some examples here:

http://msdn.microsoft.com/en-us/library/aa332127%28VS.71%29.aspx

like image 21
jspcal Avatar answered Oct 04 '22 22:10

jspcal


suggestion, you can use string.Split() to split on "tmp". then iterate the list of splitted items and print them + the array values out eg pseudocode idea only

string[] myarray = new string[] { 'val1', 'val2' };
string s = "Hello _tmp_ how is _tmp_ this possible _tmp_ in C#";
string[] items = s.Split("tmp");
for (int i = 0; i < items.Length; i++)
{
    Console.WriteLine(parts[i] + myarray[i] ) ;
}
like image 36
ghostdog74 Avatar answered Oct 04 '22 22:10

ghostdog74


I would think that Ahmad Mageed's first solution is the one to go for because array[index++] is only evaluated once when passed into the rx.Replace method..

I compiled it too to verify whether I understand it correctly or not, and sure enough it produces the following output:

Hello value1 how is value1 this possible value1 in C#...?

Has the behaviour changed with the later versions of the framework? or am I mistaken in thinking that the expected output should be:

Hello value1 how is value2 this possible value3 in C#...?

like image 30
Martin Booth Avatar answered Oct 04 '22 21:10

Martin Booth