我需要编写一些代码,在字符串中的特定关键字上执行HTML突出显示。最好的方法来做一个字符串搜索和替换
如果我有逗号分隔的字符串列表,我想对列表中的每个条目进行搜索并替换为另一个字符串。什么是最有效的方法呢?
我目前正在做一个拆分,然后一个foreach和一个Regex.Match。例如:
string wordsToCheck = "this", "the", "and";
String listArray[] = wordsToCheck.Split(',');
string contentToReplace = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";
foreach (string word in listArray)
{
if (Regex.Match(contentToReplace, word + "\\s+", RegexOptions.IgnoreCase).Success)
{
return Regex.Replace(contentToReplace , word + "\\s+", String.Format("<span style=\"background-color:yellow;\">{0}</span> ", word), RegexOptions.IgnoreCase);
}
}
我不知道这是最有效的方式,因为单词的列表来检查可以得到长期和上面的代码可能是一个循环的一部分,搜索和替换一堆内容。
看到http://stackoverflow.com/questions/711753/a-better-way-to-replace-many-strings-obfuscation-in-c – 2009-07-26 18:43:36