2

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

dins88
  • 165
  • 1
  • 8

1 Answers1

1

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>";
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • thank you for the answer, and better explanation about html. but still got same result.It's not ignoring case. – dins88 Sep 23 '20 at 11:15
  • the problem is `if (SourceText.contains(SearchText)) {` here `contains` is case sensitive. I'm going to accept this answer because of the improvement of my code. – dins88 Sep 24 '20 at 05:57
  • 1
    @dins88 Your code in the question does not contain the code with `.contains`. Of course it does not accept a regex. If you need to find if a regex matches any string, you need to use `String.matches(regex)` or `Pattern.compile(regex).matcher(string).find()`. – Wiktor Stribiżew Sep 24 '20 at 08:14