所以,我有如下字典:
Dictionary<string, object> dict = new Dictionary<string, object>();
dict.Add("first", "Value1");
dict.Add("second", "Value2");
我有一个类似下面的字符串:
rawMsg = "My values are {first} and {second}.";
预期输出:
My values are Value1 and Value2.
字符串格式代码:
public void Format(string rawMsg, Dictionary<string, object> dict)
{
var temp = dict.Aggregate(rawMsg, (current, parameter) => current.Replace(parameter.Key, parameter.Value.ToString()));
}
要使以上代码正常工作,我需要添加以下密钥:
Dictionary<string, object> dict = new Dictionary<string, object>();
dict.Add("{first}", "Value1"); // Notice the curly braces in Keys
dict.Add("{second}", "Value2");
但是我不想在键中添加花括号。
我想以格式逻辑附加花括号。
伪代码:
public void Format(string rawMsg, Dictionary<string, object> dict)
{
// loop through all the keys and append a curly braces in them.
var temp = dict.Aggregate(rawMsg, (current, parameter) => current.Replace(parameter.Key, parameter.Value.ToString()));
}
但是我不知道一种有效的方法。请引导我。
答案 0 :(得分:3)
仅在需要时添加它?
public void Format(string rawMsg, Dictionary<string, object> dict)
{
var temp = dict.Aggregate(rawMsg, (current, parameter) => current.Replace("{" + parameter.Key + "}", parameter.Value.ToString()));
}
答案 1 :(得分:3)
如果要创建自己的字符串插值,我建议使用正则表达式,例如:
Dictionary<string, object> dict = new Dictionary<string, object>() {
{"first", "Value1" },
{"second", "Value2" },
};
string rawMsg = "My values are {first} and {second}.";
string result = Regex.Replace(
rawMsg,
@"\{[^{}]+?\}",
match => dict[match.Value.Substring(1, match.Value.Length - 2)]?.ToString());
Console.Write(result);
结果:
My values are Value1 and Value2.
PS (我),我假设您要进行所有更改,即
Dictionary<string, object> dict = new Dictionary<string, object>() {
{"first", "{second}" },
{"second", "third" },
};
string rawMsg = "My values are {{first}} and {second}.";
正确的答案是
My values are {second} and third.
否(我们不想处理second
两次)
My values are third and third.
答案 2 :(得分:1)
这应该有效。简而言之,创建一个正则表达式并将其存储在静态成员中以仅进行一次编译,然后使用其将字符串中的占位符出现(Fiddle)替换为它们的值。
private static Regex _regex = new Regex(@"(?<={)(\w+)");
...
public string Format(string rawMsg, IReadOnlyDictionary<string, object> dict) =>
_regex.Replace(rawMsg, match =>
{
string placeHolder = match.ToString();
return dict.TryGetValue(placeHolder, out object placeHolderValue)
? placeHolderValue.ToString() : null;
});
请注意,第一个正则表达式组未捕获,因此无法将大括号从捕获中排除。