强调单词

本文关键字:单词 | 更新日期: 2023-09-27 18:08:56

给定一个搜索查询:

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'">", " ");
}

这突出显示了精确匹配。然而,我想扩展它,以便当搜索词是Sheeky时突出显示Sheeky'sHighlightWords是搜索到的单词列表(没有任何过滤)。

有人知道怎么做吗?

强调单词

我认为你可以这样做:

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);
结果

This is a long string with <mark>word's</mark>, <mark>words</mark> and <mark>Words</mark>