用字典替换字符串 c#
Replace String with Dictionary c#
我需要用字典中的相应值替换所有占位符,例如 {text}
。
这是我的代码:
var args = new Dictionary<string, string> {
{"text1", "name"},
{"text2", "Franco"}
};
saveText(Regex.Replace("Hi, my {text1} is {text2}.", @"\{(\w+)\}", m => args[m.Groups[1].Value]));
问题是:如果字典中不存在输入字符串中的文本,它会抛出异常,但我宁愿用字符串 "null"
.
替换占位符
只需扩展您的 lambda:
var args = new Dictionary<string, string> {
{"text1", "name"},
{"text2", "Franco"}
};
saveText(Regex.Replace("Hi, my {text1} is {text2}.", @"\{(\w+)\}", m => {
string value;
return args.TryGetValue(m.Groups[1].Value, out value) ? value : "null";
}));
我会使用 LINQ 创建一个 Func<string, string>
一次性执行所有替换。
方法如下:
var replace = new Dictionary<string, string>
{
{ "text1", "name" },
{ "text2", "Franco" }
}
.Select(kvp => (Func<string, string>)
(x => x.Replace(String.Format("{{{0}}}", kvp.Key), kvp.Value)))
.Aggregate<Func<string, string>, Func<string, string>>(
x => Regex.Replace(x, @"\{(\w+)\}", "null"),
(a, f) => x => a(f(x)));
var result = replace( "Hi, my {text1} is {text2} and {text3} and {text4}.");
// result == "Hi, my name is Franco and null and null."
我需要用字典中的相应值替换所有占位符,例如 {text}
。
这是我的代码:
var args = new Dictionary<string, string> {
{"text1", "name"},
{"text2", "Franco"}
};
saveText(Regex.Replace("Hi, my {text1} is {text2}.", @"\{(\w+)\}", m => args[m.Groups[1].Value]));
问题是:如果字典中不存在输入字符串中的文本,它会抛出异常,但我宁愿用字符串 "null"
.
只需扩展您的 lambda:
var args = new Dictionary<string, string> {
{"text1", "name"},
{"text2", "Franco"}
};
saveText(Regex.Replace("Hi, my {text1} is {text2}.", @"\{(\w+)\}", m => {
string value;
return args.TryGetValue(m.Groups[1].Value, out value) ? value : "null";
}));
我会使用 LINQ 创建一个 Func<string, string>
一次性执行所有替换。
方法如下:
var replace = new Dictionary<string, string>
{
{ "text1", "name" },
{ "text2", "Franco" }
}
.Select(kvp => (Func<string, string>)
(x => x.Replace(String.Format("{{{0}}}", kvp.Key), kvp.Value)))
.Aggregate<Func<string, string>, Func<string, string>>(
x => Regex.Replace(x, @"\{(\w+)\}", "null"),
(a, f) => x => a(f(x)));
var result = replace( "Hi, my {text1} is {text2} and {text3} and {text4}.");
// result == "Hi, my name is Franco and null and null."