繁体   English   中英

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

请参阅在线C#演示

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM