【问题标题】:How can I perform case-insensitive pattern search and case-preserving replacement?如何执行不区分大小写的模式搜索和保留大小写的替换?
【发布时间】:2026-02-21 22:20:03
【问题描述】:

这是场景。

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

这会返回一个字符串,其中所有单词都是小写的,当然也是红色的。 我的要求是将strFormatted 作为一个字符串,其大小写与原始字符串相同,但它应该具有字体标签。

这样可以吗?

【问题讨论】:

  • 这里,根据您的代码,原始字符串将在strText,格式化后的字符串将在strFormatted
  • 是的,这不是真正的代码。这个是我编的。无论如何,我希望在用字体标签替换后,在 strFormatted 中保留 strText 的情况..

标签: java regex string replaceall


【解决方案1】:

您可以使用反向引用。比如:

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

【讨论】:

    【解决方案2】:

    我想建议使用 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);
    

    【讨论】:

    • 你为什么会这样建议?表现?可维护性?其他原因?