Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace multiple occurrences in single pass?

Tags:

c#

regex

.net-3.5

I have the following string:

abc
def
abc
xyz
pop
mmm
091
abc

I need to replace all occurrences of abc with the ones from array ["123", "456", "789"] so the final string will look like this:

123
def
456
xyz
pop
mmm
091
789

I would like to do it without iteration, with just single expression. How can I do it?

like image 863
Pablo Avatar asked Dec 24 '22 15:12

Pablo


2 Answers

Here is a "single expression version":

edit: Delegate instead of Lambda for 3.5

string[] replaces =  {"123","456","789"};
Regex regEx = new Regex("abc");
int index = 0;
string result = regEx.Replace(input, delegate(Match match) { return replaces[index++];} ); 

Test it here

like image 113
CSharpie Avatar answered Jan 06 '23 13:01

CSharpie


do it without iteration, with just single expression

This example uses the static Regex.Replace Method (String, String, MatchEvaluator) which uses a MatchEvaluator Delegate (System.Text.RegularExpressions) that will replace match values from a a queue and returns a string as a result:

var data =
@"abc
def
abc
xyz
pop
mmm
091
abc";

var replacements = new Queue<string>(new[] {"123", "456", "789"});

string result =  Regex.Replace(data, 
                             "(abc)",   // Each match will be replaced with a new 
                              (mt) =>   // queue item; instead of a one string.
                                     { 
                                       return replacements.Dequeue();
                                     });

Result

123
def
456
xyz
pop
mmm
091
789

.Net 3.5 Delegate

whereas I am limited to 3.5.

Regex.Replace(data, "(abc)",  delegate(Match match) { return replacements.Dequeue(); } )
like image 39
ΩmegaMan Avatar answered Jan 06 '23 11:01

ΩmegaMan