Dale Julian
Dale Julian

Reputation: 1588

Regex: Highlight an input in any case in TextView

I am implementing a search function on an app with the search results having the search keyword highlighted.

enter image description here

I have implemented this so far and it partially works:

public static String searchHighlightedKeyword(String keyword, String whole) {
    String highlighted = "<font color='#1e499f'><b>" + keyword +"</b></font>";
    return whole.replaceAll(keyword, highlighted);
}

However, it doesn't work when the cases don't match: enter image description here

I figured I have to implement some sort of RegEx to achieve this but I don't have an idea how.

Upvotes: 1

Views: 230

Answers (2)

Deˣ
Deˣ

Reputation: 4371

Try this

  public void searchHighlightedKeyword(TextView textView, String keyword, String whole) {
        int startPos = whole.toLowerCase().indexOf(keyword.toLowerCase());
        if (startPos < 0) {
            textView.setText(whole);
            return;
        }
        int endPos = startPos + keyword.length();
        SpannableString spannable2 = new SpannableString(whole);
        spannable2.setSpan(new ForegroundColorSpan(Color.RED), startPos, endPos,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        textView.setText(spannable2);
    }

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626927

Use a case insensitive modifier to match the keyword (which you can also Pattern.quote to make matching safer as it escaped special regex metacharacters) and a $0 backreference to the whole match:

public static String searchHighlightedKeyword(String keyword, String whole) {
    String highlighted = "<font color='#1e499f'><b>$0</b></font>";
    return whole.replaceAll("(?i)" + Pattern.quote(keyword), highlighted);
}

Here,

  • "(?i)" - an inline case insensitive modifier
  • Pattern.quote(keyword) - a keyword with all special regex metacharacters escaped (so as ( or ) could not throw an exception)
  • $0 - in the replacement string, references the whole match value.

Upvotes: 2

Related Questions