对于每个新发现的值,将字符串中的键替换为一些不同的值


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

通过使用

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

每个找到的guid的值都是相同的,如何为每个找到的新值进行更改?

您可以使用Regex。替换:

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

每次比赛都会调用匹配评估器,并且可以很容易地为每次调用返回不同的替换项

我创建了一个与当前相匹配的微小扩展方法

/// <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;
}

我不知道为什么没有像这样的C#函数,但它运行得很好。

我用你的例子做了一个小单元测试(使用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");
}

最新更新