【发布时间】:2010-11-14 04:30:45
【问题描述】:
我需要编写一些代码来对字符串中的特定关键字执行 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);
}
}
我不确定这是最有效的方法,因为要检查的单词列表可能会很长,并且上面的代码可能是搜索和替换一堆内容的循环的一部分。
【问题讨论】:
-
我最终使用了这个代码:Regex.Replace(contentToReplace, wordsToCheck + "\\s+", "$1 ", RegexOptions.Singleline | RegexOptions.IgnoreCase);