How to replace text using ReplaceFirst() without case sensitivity

Viewed 48

I'm trying to create a method which can highlight text in a jlabel according user entered search text. it works fine except it case sensitive. I used a regex (?i) to ignore case. But still it case sensitive.

private void jTextField1KeyReleased(java.awt.event.KeyEvent evt) {                                        
        String SourceText = "this is a sample text";
        String SearchText = jTextField1.getText();

        if (SourceText.contains(SearchText)) {
            String OutPut = "<html>" + SourceText.replaceFirst("(?i)" + SearchText, "<span style=\"background-color: #d5f4e6;\">" + SearchText + "</span>") + "</html>";
            jLabel1.setText(OutPut);
        } else {
            jLabel1.setText(SourceText);
        }
    }

How can i fix this.

Update

contains is case sensitive.

How to check if a String contains another String in a case insensitive manner in Java

1 Answers

You have not used the matched text in the replacement, you hard-coded the same string you used in the search. Since you wrap the whole match with html tags, you need to use the $0 backreference in the replacement (it refers to the whole match that resides in Group 0).

Besides, you have not escaped ("quoted") the search term, it may cause trouble if the SearchText contains special regex metacharacters.

You can fix the code using

String OutPut = "<html>" + SourceText.replaceFirst("(?i)" + Pattern.quote(SearchText), "<span style=\"background-color: #d5f4e6;\">$0</span>") + "</html>";
Related