英文:
The given key was not present in the dictionary Match Evaluator delegate
问题
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));
string str2 = p.Replace(str1, x => dict[x.Value]);
英文:
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]);
答案1
得分: 1
你应该Escape具有正则表达式中特殊含义的符号(例如?
):
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]);
有一个小技巧是使用.OrderByDescending(key => key.Length)
:如果我们有一个模式是另一个模式的子字符串,比如
{"--", "x2"},
{"-", "x1"}, // "-"是"--"的子字符串
那么我们应该首先尝试更长的模式:--abc
应该被转换为x2abc
,而不是x1x1abc
。
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论