【问题标题】:Highlight search word with apostrophe android用撇号 android 突出显示搜索词
【发布时间】: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


    【解决方案1】:

    您可以在searchQuery 中的每个字符之间添加['’]? 模式(匹配可选的' 字符):

    Pattern word = Pattern.compile(TextUtils.join("['’]?", searchQuery.split("")), Pattern.CASE_INSENSITIVE);
    

    这样,您将确保搜索短语匹配,即使其中有一个撇号。

    查看regex demo

    【讨论】:

    • Stiizew 我有一个类似的用例。 "searchQuery.split("")" 中的 ("") 有什么作用?
    • @AJW 它将字符串拆分为单独的字符。
    猜你喜欢
    • 1970-01-01
    • 2017-01-23
    • 1970-01-01
    • 2012-08-04
    • 2012-05-21
    • 2014-02-13
    • 2015-01-28
    相关资源
    最近更新 更多