Search code examples
c#regex.net-3.5

How to replace multiple occurrences in single pass?


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?


Solution

  • 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