Skip to main content
 首页 » 编程设计

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

2024年02月27日34mate10pro

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

这就是我正在尝试的:

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)); 

参见 online C# demo .

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