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

前端 未结 2 734
梦毁少年i
梦毁少年i 2021-01-21 18:44

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 = s         


        
相关标签:
2条回答
  • 2021-01-21 19:25

    You can use a backreference. Something like:

    String strFormatted = strText.replaceAll(
        "(?i)(" + searchText + ")", 
        "<font color='red'>$1</font>");
    
    0 讨论(0)
  • 2021-01-21 19:43

    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);
    
    0 讨论(0)
提交回复
热议问题