我有一個sql結果集,它是在使用LIKE關鍵字搜索數據庫後檢索的。我想在頁面上顯示結果,但不顯示整個文本。只是找到結果的段落。甚至可能會把這個特別的單詞加粗。任何人都知道我如何最好地實現這一點?在Haystack中查找字符串並顯示找到該字符串的特定段落
0
A
回答
2
- 將文本轉換爲字符串。
- 分割你的段落字符(換行符) -
text.split('\n')
- 遍歷每個段落
- 讓您的關鍵字的索引(ES) -
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;
}
相關問題
- 1. 如何在段落中查找並添加粗體字符串?
- 2. 在字符串中查找字符串
- 3. 從字符串值中查找特定的字符串數組
- 4. 查找HTML字符串中字符串的顯示高度
- 5. 查找字符串中的字符串
- 6. 在Matlab中查找字符串中的特定字符
- 7. 查找字符串中的特定特殊字符
- 8. 查找特定字符串的一列中,並找到對應於串最大
- 9. 如何查找給定字符串中的特定字符?
- 10. 查找特定的字符串
- 11. 查找並替換字符串中的特殊字符
- 12. isInfixOf並在字符串中查找字符串
- 13. 找到並從字符串
- 14. Python中找到該字符串匹配的隨機字符串
- 15. Rails:如何查找包含特定字符串的字段
- 16. 如何查找字符串中的兩個特定字符?
- 17. 查找字符串中特定字符集合後的值
- 18. 如何查找特定字符串內的字符串並插入
- 19. jQuery - 查找字符串並將字符串前置到它?
- 20. mysql:查找(並顯示)不在表中的字符串
- 21. 如何在字符串中找到特定字符
- 22. django haystack如何找到字詞中的子字符串?
- 23. 查找字符串
- 24. 查找字符串
- 25. 查找字符串
- 26. 查找字符串
- 27. 查找字符串
- 28. 查找字符串
- 29. 查找字符串
- 30. 如何在csv文件中搜索特定的字符串,並知道在哪一行找到該字符串?
可能是有用的http://www.codeproject.com/KB/string/fastestcscaseinsstringrep.aspx – PRR 2010-08-09 08:47:30