C#用捕获的组替换正则表达式匹配的模式

C#用捕获的组替换正则表达式匹配的模式,c#,.net,regex,C#,.net,Regex,我试图用捕获的组替换字符串中的模式,但不是直接替换。捕获组的值驻留在字典中,由捕获组本身键入。我怎样才能做到这一点 这就是我正在尝试的: string body = "hello [context.world]!! hello [context.anotherworld]"; Dictionary<string, string> dyn = new Dictionary<string, string>(){ {"world", "earth"}, {"anotherwor

我试图用捕获的组替换字符串中的模式,但不是直接替换。捕获组的值驻留在字典中,由捕获组本身键入。我怎样才能做到这一点

这就是我正在尝试的:

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"]));
string body=“你好[context.world]!!你好[context.anotherworld]”;
字典dyn=新字典({“世界”,“地球”},{“另一个世界”,“火星”});
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));
string body=“hello[context.world]!!hello[context.anotherworld]和[context.text]”;
Dictionary dyn=新字典(){
{“世界”、“地球”}、{“另一个世界”、“火星”}
};
Console.WriteLine(Regex.Replace(body,@“\[context\(\w+)”),
m=>dyn.ContainsKey(m.Groups[1].Value)?dyn[m.Groups[1].Value]:m.Value);

首先检查字典是否包含键。如果没有,只需重新插入匹配项,否则返回相应的值