将字符串替换为字典 c#

本文关键字:字典 替换 字符串 | 更新日期: 2023-09-27 18:36:50

我需要将所有占位符(如{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" .

将字符串替换为字典 c#

只需展开你的 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."

OP 似乎正在尝试解决渲染模板的问题。虽然使用正则表达式很有趣,但模板引擎很好地解决了渲染模板的问题。

一个好的模板语言是胡

子,一个好的模板引擎是胡茬。即使你没有利用模板引擎的所有功能,整体代码仍然简洁:

using Stubble.Core.Builders;
...
var args = new Dictionary<string, string> {
   {"text1", "name"},
   {"text2", "Franco"}
};
var stubble = new StubbleBuilder().Build();
saveText(stubble.Render("Hi, my {{text1}} is {{text2}} and {{text3}} and {{text4}}")

存茬的默认行为是将未知占位符呈现为空。但是,您可以添加默认值,例如值为"null"的字符串:

var stubble = new StubbleBuilder().Configure(settings =>
{
  settings.AddValueGetter(typeof(object), (key, value, ignoreCase) => "null");
}).Build();
Dictionary<string, object> args = new Dictionary<string, object> {
  {"text1", "name"},
  {"text2", "Franco"}
};
saveText(stubble.Render("Hi, my {{text1}} is {{text2}} and {{text3}} and {{text4}}")