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?
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?
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
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");
}