C# 突出显示单词
给定搜索查询:C# 突出显示单词,c#,regex,algorithm,highlight,C#,Regex,Algorithm,Highlight,给定搜索查询: Sheeky's 将删除特殊字符,并将其小写为: sheekys 相同的过滤器应用于我正在搜索的数据库中的字段。这是为了搜索: sheekys 将返回名为的项目的结果: Sheeky's Item 这是过滤器: public static string FilterSearchQuery(string query) { return Regex.Replace(query, "[^0-9A-Za-z ]", ""); } 在“搜索结果”视图中,匹配的单词高亮显示
Sheeky's
将删除特殊字符,并将其小写为:
sheekys
相同的过滤器应用于我正在搜索的数据库中的字段。这是为了搜索:
sheekys
将返回名为的项目的结果:
Sheeky's Item
这是过滤器:
public static string FilterSearchQuery(string query)
{
return Regex.Replace(query, "[^0-9A-Za-z ]", "");
}
在“搜索结果”视图中,匹配的单词高亮显示,如下所示:
public string HighlightText(string text)
{
foreach (var word in HighlightWords)
{
var findWord = word.Trim();
if (findWord.Length > 0)
{
var itemRegex = new Regex(findWord, RegexOptions.IgnoreCase);
foreach (var match in itemRegex.Matches(text))
{
text = text.Replace(match.ToString(),
"¬¬¬¬¬¬¬____¬¬¬¬¬¬" + match.ToString() + "````````____`````");
}
}
}
text = text.Replace("¬¬¬¬¬¬¬____¬¬¬¬¬¬", "<span class=\"highlighted\">");
text = text.Replace("````````____`````", "</span>");
return text.Replace("</span> <span class=\"highlighted\">", " ");
}
公共字符串高亮文本(字符串文本)
{
foreach(HighlightWords中的var单词)
{
var findWord=word.Trim();
如果(findWord.Length>0)
{
var itemRegex=new Regex(findWord,RegexOptions.IgnoreCase);
foreach(itemRegex.Matches中的变量匹配(文本))
{
text=text.Replace(match.ToString(),
“match.ToString()”+“``````````````````````````````````”;
}
}
}
文本=文本。替换为“,,”;
text=text.Replace(```````````uuuuu```````、“”);
返回文本。替换(“,”);
}
这突出了精确匹配的细节。但是,我想扩展它,以便在搜索词为Sheeky
时突出显示Sheeky的
HighlightWords
是搜索的单词列表(无任何筛选)
有人知道怎么做吗?我想你可以做到:
var itemRegex = new Regex(findWord + ".*", RegexOptions.IgnoreCase);
上面的内容将匹配Sheeky以及之后的任何内容 问题是在原始文本中查找匹配项,而忽略非字母。有了一些正则表达式的魔力,这是可行的:
var content = "This is a long string with word's, words and Words"; // the text to search in
var tofind = "W'ords"; // the text to search for
// prepare search value: remove non-letters/digits, set to lowercase
tofind = Regex.Replace(tofind, @"\W", "").ToLower();
// create search regex: allow non-letter between the letters
var findregex = String.Join(@"\W*", tofind.ToCharArray().Select(c => c.ToString()));
// surround matches with a <mark> tag
var content2 = Regex.Replace(content, findregex, "<mark>$0</mark>", RegexOptions.IgnoreCase);
var content=“这是一个包含单词、单词和单词的长字符串”//要搜索的文本
var tofind=“W'ords”//要搜索的文本
//准备搜索值:删除非字母/数字,设置为小写
tofind=Regex.Replace(tofind,@“\W”和“”).ToLower();
//创建搜索正则表达式:允许字母之间不包含字母
var findregex=String.Join(@“\W*”,tofind.tocharray().Select(c=>c.ToString());
//用标签把火柴围起来
var content2=Regex.Replace(content,findregex,“$0”,RegexOptions.IgnoreCase);
结果是
这是一个包含单词、单词和单词的长字符串
如果搜索词是
sheekys
它不会匹配sheekys
,但会匹配sheekys'
@TomGullen,你需要提供一些特定的规则(比如撇号),因为如果你要使用regex解析语法,它将无法工作。如果我理解正确,当前算法只突出显示Sheeky的
中的Sheeky
,您希望它突出显示整个单词(如在非空格字符中)?您也许可以使用newregex(findWord+@“\S*”,RegexOptions.IgnoreCase)代码>相反?旁注:还有一个用于突出显示的标记。它比这个复杂一点,不是吗?您还必须匹配任意数量的前导(@!~sheeky)和尾随(sheeky~$%)特殊字符,对吗?