2017-04-06 31 views
1

我想用捕獲的組替換我的字符串中的模式,但不是直接。捕獲組的值駐留在字典中,由捕獲的組自己鍵入。我怎樣才能做到這一點?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得到字典查找期間字面解釋。

回答

3

你需要在比賽傳遞給匹配評價是這樣的:

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

檢查字典是否包含密鑰。如果沒有,只需重新插入匹配,否則返回相應的值。

+1

完美。謝謝 – user949110