Loop through all of the occurrences of a certain string and replace each with a different value in C#?

Viewed 553

I have a large text string (its a source code), and i need to loop through occurrences of a certain string (which can occur in random number of places), and replace each of them with a different value, which i cannot do using Replace() function considering it replaces all the of them with a unique value.

so for example this text string :

REPLACE_ME

REPLACE_ME

REPLACE_ME

needs to get converted to this :

RAND_STRING1

RAND_STRING2

RAND_STRING3

I read the entire text all at once, and already have it in a string variable.

3 Answers

Regex.Replace() accepts a MatchEvaluator delegate with which you can accomplish what you want:

var input = "REPLACE_ME REPLACE_ME REPLACE_ME";

var substring = Regex.Escape("REPLACE_ME");
var substitute = "VALUE";
var counter = 1;

var result = Regex.Replace(input, substring, (m) => $"{prefix}{counter++}");

Value of result will be "VALUE1 VALUE2 VALUE3".

The Regex.Escape() call is redundant for this particular example ("REPLACE_ME" doesn't contain any special characters that needs to be escaped), but I suggest getting into the habit of escaping literal substrings regardless - especially if you want to accept user-supplied input!

Of course you can do anything you'd like in the evaluator:

var random = new Random();
var result = Regex.Replace(input, substring, (m) => random.Next().ToString());
// or
var result = Regex.Replace(input, substring, (m) => {
    var randomString = someAPIClient.GetRandomValueFromRandomValueService();
    var encoded = Encoding.UTF8.GetBytes(randomString);
    return Convert.ToBase64String(encoded);
});

Your imagination sets the limit here :)

regex example:

string[] textFile = File.ReadAllLines("myFile.txt");
var i = 0;
//Stringbuilder will be the contents of our new text file.
StringBuilder sb = new StringBuilder();
//iterate through each line, making our replacements and appending to the string builder
foreach (string line in textFile)
{
    var result = Regex.Replace(
                 line, "REPLACE_ME", m => string.Format("{0}{1}",m.Value,++i), RegexOptions.IgnoreCase);
    sb.AppendLine(result);
}
//Write to new file like so:
StreamWriter sw = new StreamWriter("newFile.txt");
sw.Write(sb.ToString()));
sw.Close();

You need to traverse the file line by line. Keep a counter of nr instances found.

If the current line contains your REPLACE_ME string then replace that string with your random string and append the counter value, update the counter + 1 and keep going to the following line.

The result will be that each instance of your replace_me will be replace with a unique value.

Related