var formatString = "{a}xxxx{b}xxx{c}xxx{d}xxx{e}xxx";
Dictionary<string, string> dic = new Dictionary<string, string>
{
{ "a","xxxx" },
{ "b","xxx" },
{ "c","x" },
{ "e","xxxxxx" },
{ "d","xxxxxxx" },
};
如上:
如何使用dic中的值去替换formatString {\w+} 字符串呢
有木有大神知道, 请指点感激不尽
var formatString = "{a}xxxx{b}xxx{c}xxx{d}xxx{e}xxx";
var dic = new Dictionary<string, string>
{
{ "a","bv" },
{ "b","av" },
{ "c","cv" },
{ "e","ev" },
{ "d","dv" },
};
var reg = new Regex(@"{([\w])+}");
var buff = new StringBuilder();
var arr = reg.Split(formatString);
for (int i = 0; i < arr.Length; i++)
{
if (i%2 == 0) continue;
var key = arr[i];
if (dic.TryGetValue(key, out key))
{
arr[i] = key;
}
}
var str = string.Concat(arr);
我自己刚研究了一下, 不知道这样可行不, 还有木有更好的方式呢
static Dictionary<string, string> dic = new Dictionary<string, string> { { "a","bv" }, { "b","av" }, { "c","cv" }, { "e","ev" }, { "d","dv" }, }; static void Main(string[] args) { var formatString = "{a}xxxx{b}xxx{c}xxx{d}xxx{e}xxx{t}"; var reg = new Regex(@"(\{(\w+)\})"); formatString = reg.Replace(formatString, new MatchEvaluator(FromDic)); Console.WriteLine(formatString); Console.ReadKey(); } private static string FromDic(Match match) { string value = ""; if (dic.TryGetValue(match.Groups[2].Value, out value)) return value; return match.Groups[0].Value; }
大神, 这个不错,
之前一直木有发现reg.Replace 还有MatchEvaluator 这个重载
遍历字典的key,替换对应字符串 。
foreach(var item in dic.Keys) {
var value = string.Empty; dic.TryGetValue(item,out value); formatString = formatString.Replace(item, value); }
这样性能不太好吧
@Mirck: 字典性能应该没啥问题吧,再说你能有多少个key?
@clarlespeng: 应该有几十个子吧, 然后 很多其实没有用到, 也会进行一次Replace(item, value);
@Mirck: 恩 如果有真实数据 动手对比下 就会知道了 哪个好 就用那个。
不过几十个这个量级 应该不会牵扯到性能问题 。找最优解测试 应该有更大的量级