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:
using System.Linq;
using System.Text.RegularExpressions;
...
IDictionary<string, string> dict = new Dictionary<string, string>() {
{ "-", "e" },
{ "?", "z'" },
};
var pattern = string.Join("|", dict
.Keys
.OrderByDescending(key => key.Length)
.Select(key => Regex.Escape(key)));
string str1 = "-50";
string str2 = Regex.Replace(str1, pattern, match => dict[match.Value]);
There is a little trick with .OrderByDescending(key => key.Length)
: if we have pattern which is a substring of another one, say
{"--", "x2"},
{"-", "x1"}, // "-" is a substring of "--"
then we should try longer pattern first: --abc
should be transformed into x2abc
, not x1x1abc