代码之家  ›  专栏  ›  技术社区  ›  Churchill

在Haystack中查找字符串并显示找到该字符串的特定段落

  •  0
  • Churchill  · 技术社区  · 15 年前

    我有一个sql resultset,它是在使用LIKE关键字搜索数据库之后检索的。我想将结果显示在一页上,但不显示整个文本。只是找到结果的那一段。甚至可以用粗体写下这个词。有谁知道我怎样才能做到最好吗?

    1 回复  |  直到 15 年前
        1
  •  2
  •   Mikael Svenson    15 年前
    • 把文本串成一个字符串。
    • text.split('\n')
    • 在每个段落上迭代
    • text.IndexOf("keyword")
    • 然后执行一些逻辑来减少开头和结尾的字符数
    • 插入粗体标记,例如字符串替换- text = text.Replace("keyword", "<b>keyword</b>")

    public List<string> HighLightedParagraphs(string word, string text)
    {
        int charBeforeAndAfter = 100;
        List<string> matchParagraphs = new List<string>();
        Regex wordMatch = new Regex(@"\b" + word + @"\b", RegexOptions.IgnoreCase);
        foreach (string paragraph in text.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries))
        {
            int startIdx = -1;
            int length = -1;
            foreach (Match match in wordMatch.Matches(paragraph))
            {
                int wordIdx = match.Index;
                if (wordIdx >= startIdx && wordIdx <= startIdx + length) continue;
                startIdx = wordIdx > charBeforeAndAfter ? wordIdx - charBeforeAndAfter : 0;
                length = wordIdx + match.Length + charBeforeAndAfter < paragraph.Length
                                    ? match.Length + charBeforeAndAfter
                                    : paragraph.Length - startIdx;
                string extract = wordMatch.Replace(paragraph.Substring(startIdx, length), "<b>" + match.Value + "</b>");
                matchParagraphs.Add("..." + extract + "...");
            }
        }
        return matchParagraphs;
    }