簡體   English   中英

高亮詞

[英]Highlight words

給定一個搜索查詢:

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's 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);

結果是

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM