Search code examples
javaregexstringreplaceall

How can I perform case-insensitive pattern search and case-preserving replacement?


Here is the scenario.

String strText = "ABC abc Abc aBC abC aBc ABc AbC";
// Adding a HTML content to this
String searchText = "abc";
String strFormatted = strText.replaceAll(
    "(?i)" + searchText, 
    "<font color='red'>" + searchText + "</font>");

This returns a string with all the words in lower case and of course in red color. My requirement is to get the strFormatted as a String with the case same as Original String but it should have the Font tag.

Is it possible to do this ?


Solution

  • You can use a backreference. Something like:

    String strFormatted = strText.replaceAll(
        "(?i)(" + searchText + ")", 
        "<font color='red'>$1</font>");