2
var myString = "$guid$! test $guid$, here another test string and then $guid$";

by using

myString.Replace("$guid$", Guid.NewGuid().ToString()))

the value for every found guid will be the same, how to change for every found new value?

Alex
  • 8,908
  • 28
  • 103
  • 157
  • Not a 100% duplicate, but this should be a good starting point: https://stackoverflow.com/q/8809354/2422776 – Mureinik Aug 09 '20 at 09:18
  • https://stackoverflow.com/questions/141045/how-do-i-replace-the-first-instance-of-a-string-in-net – mjwills Aug 09 '20 at 09:22

2 Answers2

2

You could use Regex.Replace:

var replaced = Regex.Replace(myString, @"\$guid\$", match => Guid.NewGuid().ToString());

The match evaluator will be called for every match and can easily return different replacements for each call

Klaus Gütter
  • 11,151
  • 6
  • 31
  • 36
0

I create a tiny extension method that match the currents one

/// <summary>
/// Returns a new string in which all occurences of a specified string in this instance are replaced with a runtime determined string 
/// </summary>
/// <param name="oldValue">the string to be replaced</param>
/// <param name="newValue">the function used to replace the string called one time per occurence</param>
public static string Replace(this string text, string oldValue, Func<string> newValue)
{
    var replacedText = new StringBuilder();
    int pos = text.IndexOf(oldValue);
    while (pos >= 0)
    {
        var nv = newValue();
        replacedText.Append(text.Substring(0, pos) + nv);
        text = text.Substring(pos + oldValue.Length);
        pos = text.IndexOf(oldValue);
    }
    return replacedText + text;
}

I don't know why there is no existing C# function like this but it works nice.

I make a tiny unit test with your example (using NFluent) :

[TestMethod]
public void ReplaceTest()
{
    var i = 1;
    Check.That("$guid$! test $guid$, here another test string and then $guid$"
        .Replace("$guid$", () => (i++).ToString()))
        .IsEqualTo("1! test 2, here another test string and then 3");
}
Orkad
  • 630
  • 5
  • 15
  • `I don't know why there is no existing C# function like this but it works nice.` Likely because it was easy for you to write, and useful in only rare circumstances. :) – mjwills Aug 09 '20 at 10:15
  • @mjwills haha yes its true. – Orkad Aug 09 '20 at 10:20