import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @Author: * @Date: 2022/6/13 17:35 * @Description: 通用工具 * @Version: v1.0 */ public class ComUtil { /** * 实现不区分大小写高亮替换 * * @param source * @param patternString * @return */ public static String ignoreCaseReplace(String source, String patternString) { Pattern p = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE); Matcher mc = p.matcher(source); StringBuffer sb = new StringBuffer(); while (mc.find()) { mc.appendReplacement(sb, "<font color='red' >" + mc.group() + "</font>"); } mc.appendTail(sb); return sb.toString(); } public static void main(String[] args) { String a = "ABCDabcd哈哈"; String b = "b"; System.out.println(ignoreCaseReplace(a, b)); } }
输出:A<font color='red' >B</font>CDa<font color='red' >b</font>cd哈哈