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

C# Replace regex matched pattern with a captured group

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

这就是我正在尝试的:

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[""]));

我不断收到 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));

参见online C# demo

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