简体   繁体   中英

C# Replace regex matched pattern with a captured group

I am trying to replace a pattern in my string with a captured group, but not directly. The value for the captured group resides in a dictionary, keyed by the captured group itself. How can I achieve this?

This is what I'm trying:

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

I keep getting KeyNotFoundException which indicates to me that the $1 is getting interpreted literally during dictionary lookup.

You need to pass the match to a match evaluator like this:

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

See the online C# demo .

Check if the dictionary contains the key first. If it doesn't, just re-insert the match, else, return the corresponding value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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