C#用捕获的组替换正则表达式匹配的模式
问题描述:
我想用捕获的组替换我的字符串中的模式,但不是直接。捕获组的值驻留在字典中,由捕获的组自己键入。我怎样才能做到这一点?C#用捕获的组替换正则表达式匹配的模式
这就是我想:
string body = "hello [context.world]!! hello [context.anotherworld]";
Dictionary<string, string> dyn = new Dictionary<string, string>(){ {"world", "earth"}, {"anotherworld", "mars"}};
Console.WriteLine(Regex.Replace(body, @"\[context\.(\w+)\]", dyn["$1"]));
我不断收到KeyNotFoundException这表明对我来说,$ 1得到字典查找期间字面解释。
答
你需要在比赛传递给匹配评价是这样的:
string body = "hello [context.world]!! hello [context.anotherworld] and [context.text]";
Dictionary<string, string> dyn = new Dictionary<string, string>(){
{"world", "earth"}, {"anotherworld", "mars"}
};
Console.WriteLine(Regex.Replace(body, @"\[context\.(\w+)]",
m => dyn.ContainsKey(m.Groups[1].Value) ? dyn[m.Groups[1].Value] : m.Value));
检查字典是否包含密钥。如果没有,只需重新插入匹配,否则返回相应的值。
完美。谢谢 – user949110