简体   繁体   中英

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 ?

You can use a backreference. Something like:

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

I'd like to suggest an alternative using ArrayList

String [] strText = {"ABC", "abc","Abc", "aBC", "abC", "aBc", "ABc", "AbC"};

    ArrayList<String> abc = new ArrayList<String> ();
       for(int j=0;j<8;j++)
        {

           if("abc".equalsIgnoreCase(strText[j]))
                  {
                      abc.add("<font color='red'>"+strText[j]+"</font>");
                  }
        }

   String strFormatted = abc.toString();
   System.out.println(strFormatted);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM