Regex replace - how to replace the same template in different places with different lines?

I have a peculiar problem ..!

I have a string with some constant value in a few steps. 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 the values โ€‹โ€‹that are stored in the array, first tmp contains the array [0], the second tmp contains the array [1] and so on ...

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

+6
c # regex
source share
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 make sure that the number of matches found never exceeds the length of the array, as shown above.

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

 string result = rx.Replace(input, delegate(Match m) { return array[index++]; }); 
+4
source share

you can use MatchEvaluator (function called for each replacement), some examples here:

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

+2
source share

you can use string.Split () to split into "tmp". then iterate over the list of split elements and print them + array values, for example, only the idea of โ€‹โ€‹pseudocode

 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] ) ; } 
+1
source share

I would think that the first solution of Ahmad Mageed is that array [index ++] is evaluated only once when it is passed to the rx.Replace method ..

I also compiled it to check whether I understood it correctly or not, and, of course, it produces the following output:

Hello1 value as value1 this possible value1 in C # ...?

Is the behavior changed in later versions of the structure? or am I mistaken in thinking that the expected result should be:

Hi, value1, how is value2 is possible value3 in C # ...?

+1
source share

All Articles