【发布时间】:2021-06-24 07:58:36
【问题描述】:
我在我的 android 应用程序中使用 FTS4 来实现全文搜索。应用程序中的数据来自 API,具有变音符号和口音。我在数据库中创建了两列,一列存储原始数据,另一列存储没有变音符号或重音符号的数据(使用 Normalizer 剥离)。当我搜索没有变音符号或重音符号的单词时,搜索成功执行。当我想突出显示在文本中找到的搜索查询时,就会出现问题。
例如。这句话里面I got from SO:
James 问:“这是 Renée 和 Noël 的曾祖父母在 1970 年代的避暑别墅,不是吗?”没有得到回应,他摇了摇头——然后走开了。
如果我搜索 Renee,它会突出显示 Renée,但是当我执行搜索 Renee 时,它会成功找到包含单词 Renée's 的文本,但由于撇号,它不会突出显示它。
Search Term: Renee
Highlighted Output: Renée
Search Term: Renees
Highlighted Output: <whitespace>Renée’ <-- doesn't show the expected output
Expected Output: Renée’s
如果我使用 replaceAll 删除所有撇号以突出显示搜索到的查询,它将显示突出显示的单词 Renée's 但只显示像这样的撇号 -> Renée' 甚至突出单词前的空格。但如果段落中有更多的撇号已被删除,它会将突出显示的单词推回更多。
基本上我想在显示给用户的段落中显示 Renée's 并突出显示整个单词,即使用户搜索 Renees。
这是我突出显示搜索文本的代码:
if (searchQuery != null){
String paragraph = data.getParagraph();
SpannableStringBuilder sb = new SpannableStringBuilder(paragraph);
String normalizedText = Normalizer.normalize(paragraph, Normalizer.Form.NFD).replaceAll("\\p{InCombiningDiacriticalMarks}+", "").toLowerCase();
//String normalizedText = Normalizer.normalize(paragraph, Normalizer.Form.NFD).replaceAll("\\p{InCombiningDiacriticalMarks}+", "").replaceAll("'", "").toLowerCase(); //remove all apostrophes -- this works but pushes back the highlighted text color because it doesn't count all stripped apostrophes in the original paragraph.
Pattern word = Pattern.compile(searchQuery, Pattern.CASE_INSENSITIVE);
Matcher match = word.matcher(normalizedText);
while (match.find()) {
BackgroundColorSpan fcs = new BackgroundColorSpan(Color.YELLOW);
sb.setSpan(fcs, match.start(), match.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
text.setText(sb);
}
即使使用撇号,我如何突出显示搜索的单词?
【问题讨论】:
标签: android regex highlight matcher