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?
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
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(); } )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With