I'm trying to replace a string with regex via Match Evaluator delegate. [dictionary method] when the string starts with: .- &*?. I get a error with the following details:
the given key was not present in the dictionary.
What can I do?
IDictionary<string, string> dict = new Dictionary<string, string> ()
{
{ "-", "e" },
{ "?", "z'" },
};
string str1 = "-50"
var p = new Regex(String.Join("|", dict.Keys));
str2 = p.Replace(str1, x => dict[x.Value]);
You should Escape symbols (e.g.
?) which have special meaning in regular expressions:There is a little trick with
.OrderByDescending(key => key.Length): if we have pattern which is a substring of another one, saythen we should try longer pattern first:
--abcshould be transformed intox2abc, notx1x1abc