簡體   English   中英

在Java中突出顯示搜索關鍵字

[英]Highlight search keyword in java

在我的作業中,我正在使用solr進行搜索。

  1. 它可以正常工作,並在結果標頭中以片段大小為200的突出顯示的關鍵字返回結果。
  2. 當我單擊結果時,標題將展開並顯示整個結果。

我的問題是,我還需要在打開的結果中突出顯示關鍵字。 我怎樣才能做到這一點? 我可以用solr來做還是只需要在Java中做呢?

以下兩個鏈接應該可以幫助您:

更新的答案:

一種簡單的解決方案可能是遍歷搜索的單詞,然后在顯示結果之前將其替換為結果:

// warning: pseudcode ahead
List<String> newResults = new ArrayList<String>();
for(String result : search.getResults()) { // pseudocode, don't know the exact interface
  for(String word : searchQuery.split("\\s+")) {
    newResults.add(result.replaceAll(word, "<strong>" + word + "</strong>"));
  }
}

不區分大小寫的解決方案:

    String searchTerm="test", result="This is a TEST";
    Pattern pattern = Pattern.compile("(" + Pattern.quote(searchTerm.toLowerCase()) + ")",
            Pattern.CASE_INSENSITIVE | Pattern.DOTALL);

    result = pattern.matcher(result).replaceAll("<strong>$1</strong>");

參見https://docs.oracle.com/javase/tutorial/essential/regex/pattern.html

暫無
暫無

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

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