简体   繁体   English

在Java中突出显示搜索关键字

[英]Highlight search keyword in java

In my assignment I'm doing a search using solr. 在我的作业中,我正在使用solr进行搜索。

  1. It works fine and returns result with highlighted keywords with fragment size 200 in header of result. 它可以正常工作,并在结果标头中以片段大小为200的突出显示的关键字返回结果。
  2. When I click on the result, the header expands and shows whole result. 当我单击结果时,标题将展开并显示整个结果。

My problem is that I need to highlight keywords in opened results as well. 我的问题是,我还需要在打开的结果中突出显示关键字。 How can I do that? 我怎样才能做到这一点? Can I do it with solr or do I need to do it in java only? 我可以用solr来做还是只需要在Java中做呢?

The following two links should get you going: 以下两个链接应该可以帮助您:

Updated Answer: 更新的答案:

One simple solution might be to iterate over the words of your search and replace them in the result before displaying it: 一种简单的解决方案可能是遍历搜索的单词,然后在显示结果之前将其替换为结果:

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

Case insensitive solution: 不区分大小写的解决方案:

    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>");

see https://docs.oracle.com/javase/tutorial/essential/regex/pattern.html 参见https://docs.oracle.com/javase/tutorial/essential/regex/pattern.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM