Java | 替换内容中的多个关键字为红色样式返回给前端

实际工作中常会遇到一个这样的需求,将搜索到的关键字用红色高亮显示
keywordsList<String> 集合

for (SafetyPromotionMsg safetyPromotionMsg : selectByPage.getContent()) {
    
    
                String msgContent = safetyPromotionMsg.getMsgContent();
                for (String s : keywords) {
    
    
                    Pattern pattern = Pattern.compile("(?i)" + s.trim());
                    Matcher matcher = pattern.matcher(msgContent);
                    while (matcher.find()) {
    
    
                        msgContent = matcher.replaceAll("<span style='color: red;'>" + matcher.group() + "</span>");
                    }
                }
                safetyPromotionMsg.setMsgContent(msgContent);
            }

猜你喜欢

转载自blog.csdn.net/y1534414425/article/details/108572843