C# 字符串替换为字典 [英] C# String replace with dictionary
问题描述
我有一个字符串,我需要对其进行一些替换.我有一个 Dictionary
,其中定义了搜索替换对.我创建了以下扩展方法来执行此操作:
I have a string on which I need to do some replacements. I have a Dictionary<string, string>
where I have search-replace pairs defined. I have created following extension methods to perform this operation:
public static string Replace(this string str, Dictionary<string, string> dict)
{
StringBuilder sb = new StringBuilder(str);
return sb.Replace(dict).ToString();
}
public static StringBuild Replace(this StringBuilder sb,
Dictionary<string, string> dict)
{
foreach (KeyValuePair<string, string> replacement in dict)
{
sb.Replace(replacement.Key, replacement.Value);
}
return sb;
}
有没有更好的方法来做到这一点?
Is there a better way of doing that?
推荐答案
如果数据被标记化(即Dear $name$, as of $date$ your balance is $amount$"),则使用 Regex
很有用:
If the data is tokenized (i.e. "Dear $name$, as of $date$ your balance is $amount$"), then a Regex
can be useful:
static readonly Regex re = new Regex(@"$(w+)$", RegexOptions.Compiled);
static void Main() {
string input = @"Dear $name$, as of $date$ your balance is $amount$";
var args = new Dictionary<string, string>(
StringComparer.OrdinalIgnoreCase) {
{"name", "Mr Smith"},
{"date", "05 Aug 2009"},
{"amount", "GBP200"}
};
string output = re.Replace(input, match => args[match.Groups[1].Value]);
}
但是,如果没有这样的事情,我希望您的 Replace
循环可能与您所能做的一样多,而不会太长.如果它没有被标记化,也许可以对其进行分析;Replace
真的有问题吗?
However, without something like this, I expect that your Replace
loop is probably about as much as you can do, without going to extreme lengths. If it isn't tokenized, perhaps profile it; is the Replace
actually a problem?
这篇关于C# 字符串替换为字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!