如何执行不区分大小写的模式搜索和保留大小写的替换?

Use*_*034 2 java regex string replaceall

这是场景.

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>");
Run Code Online (Sandbox Code Playgroud)

这将返回一个字符串,其中包含小写的所有单词,当然还有红色.我的要求是strFormatted使用与原始字符串相同的情况获取字符串,但它应该具有Font标记.

是否有可能做到这一点 ?

Qta*_*tax 6

您可以使用反向引用.就像是:

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