如何处理Dictionary Key区分大小写

时间:2016-01-27 19:34:41

标签: c# regex string replace

所有。我正在尝试编写一个单词替换工具,它将一次查找并替换多个单词。这是我的代码:

IDictionary<string, string> wordDict = new Dictionary<string, string>();
wordDict[wordsToFind.Text] = wordsToReplace.Text;
string textToReplace = article.Text;
foreach (KeyValuePair<string, string> entry in wordDict)
{
        textToReplace = textToReplace.Replace(entry.Key, entry.Value);
}

wordDict只是一个键值数组,其中键是要查找的单词,值是用于替换找到的单词的单词。例如,此词典中的一个条目可能看起来像无人机 - >狗。

wordsToFind.Text和wordsToReplace.text应该是不言自明的。我只是在演示我的wordDict字典是如何设置的。

article.text变量只是包含需要替换的单词的文本块。

问题我遇到的问题是当替换词击中大写单词并且不将它们识别为要替换的单词时(区分大小写)。

不仅仅是简单地降低所有内容并替换那种方式(或者,如果你还有一种方法可以保留输出中的原始外壳,我会去降低所有内容),我试图找到一种基本上检测那些大写的方法单词,其中第一个字母大写,并且当我的wordDict变量中的单词都是小写时,用相同的大小替换它替换单词。

1 个答案:

答案 0 :(得分:1)

您可以使用Regex.Replace:

IDictionary<string, string> wordDict = new Dictionary<string, string>();
wordDict[wordsToFind.Text] = wordsToReplace.Text;
string textToReplace = article.Text;
foreach (KeyValuePair<string, string> entry in wordDict)
{
    textToReplace = Regex.Replace(textToReplace, entry.Key, entry.Value, RegexOptions.IgnoreCase);
}

但是,如果原始单词是例如&#39;无人机&#39; (D大写)和替换狗#39;然后狗的d仍然是小写的,所以你需要以不同的方式做。

相关问题