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

僤鯓⒐⒋嵵緔 提交于 2019-12-02 05:57:17

问题


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 ?


回答1:


You can use a backreference. Something like:

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



回答2:


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);


来源:https://stackoverflow.com/questions/8753163/how-can-i-perform-case-insensitive-pattern-search-and-case-preserving-replacemen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!