From 79d939473f4c2305e8f5b3aad315b8a628814ca3 Mon Sep 17 00:00:00 2001 From: iamarjun Date: Sat, 8 Feb 2025 19:52:06 +0530 Subject: [PATCH] Refactor: Use regex quote for search input in `SearchHighlightUtil` The `indicesOf` function in `SearchHighlightUtil` is refactored to use `Pattern.quote` for the search input. This ensures that any special characters in the search string are treated as literals, preventing potential `PatternSyntaxException`. In case a pattern cannot be compiled due to an invalid syntax a warning will be displayed in the logger and an empty list will be returned. Also we ensure the list is converted to immutable list to prevent unwanted modifications. --- .../internal/support/SearchHighlightUtil.kt | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/library/src/main/kotlin/com/chuckerteam/chucker/internal/support/SearchHighlightUtil.kt b/library/src/main/kotlin/com/chuckerteam/chucker/internal/support/SearchHighlightUtil.kt index 94689544..021e5e1d 100644 --- a/library/src/main/kotlin/com/chuckerteam/chucker/internal/support/SearchHighlightUtil.kt +++ b/library/src/main/kotlin/com/chuckerteam/chucker/internal/support/SearchHighlightUtil.kt @@ -6,6 +6,7 @@ import android.text.style.BackgroundColorSpan import android.text.style.ForegroundColorSpan import android.text.style.UnderlineSpan import java.util.regex.Pattern +import java.util.regex.PatternSyntaxException /** * Highlight parts of the String when it matches the search. @@ -22,10 +23,15 @@ internal fun SpannableStringBuilder.highlightWithDefinedColors( } internal fun CharSequence.indicesOf(input: String): List = - Pattern.compile(input, Pattern.CASE_INSENSITIVE).toRegex() - .findAll(this) - .map { it.range.first } - .toCollection(mutableListOf()) + try { + Pattern.quote(input).toRegex(RegexOption.IGNORE_CASE) + .findAll(this) + .map { it.range.first } + .toList() + } catch (e: PatternSyntaxException) { + Logger.warn("Unable to compile pattern for input: $input", e) + emptyList() + } internal fun SpannableStringBuilder.highlightWithDefinedColorsSubstring( search: String,