我有一个扩展,它遍历一个字符串,查找任意数量的关键字(或搜索词)的所有实例。当它找到匹配项时,它会在每个关键字周围添加span标记,以突出显示显示的关键字。
public static string HighlightKeywords( this string input, string keywords )
{
if( input == String.Empty || keywords == String.Empty )
{
return input;
}
string[] words = keywords.Split( new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries );
foreach( string word in words )
{
input = Regex.Replace( input, word, string.Format( "<span class=\"highlight\">{0}</span>", "$0" ), RegexOptions.IgnoreCase );
}
return input;
}
该方法运行良好,除非您使用与添加的span标记匹配的搜索词。
不可靠的输出示例:
高级字符串"The class is
“
关键词:"class high“
结果不可靠的HTML输出: input = "The classspan> is high“
因此,它在原始字符串中查找第一个关键字,添加修饰的HTML,然后在更改后的字符串中查找下一个关键字,添加更多的HTML并造成混乱。
在搜索每个关键字时,有没有办法避免修饰关键字?
更新:
考虑到不区分大小写很重要,我探索了各种不区分大小写的替换方法,并取得了部分成功。搜索功能通过忽略大小写来工作,但返回关键字中使用的大小写,并将其替换为原始文本,例如,搜索"HIGH“返回"The class is HIGH”。这看起来很糟糕。
所以,我又回到了使用Regex (叹息)。我设法重写了我的扩展,如下所示,这似乎工作得很好,但我想知道这个扩展到底有多有效。我欢迎任何关于改进这段代码或在没有Regex的情况下实现这一点的评论。
public static string HighlightKeywords( this string input, string keywords, string classname )
{
if( input == String.Empty || keywords == String.Empty )
{
return input;
}
string[] words = keywords.Split( new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries );
foreach( string word in words )
{
input = Regex.Replace( input, Regex.Escape( word ), string.Format( "<!--{0}-->", Regex.Unescape( "$0" ) ), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled );
}
var s = new StringBuilder( );
s.Append( input );
s.Replace( "<!--", "<span class='" + classname + "'>" ).Replace( "-->", "</span>" );
return s.ToString( );
}
https://stackoverflow.com/questions/50604931
复制相似问题