代码片段
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
public class FontUtils {
//高亮替换
public static String cssTitle(String keyWord,String title) {
if(StringUtils.isNotEmpty(keyWord)) {
//不区分大小写
Pattern pattern = Pattern.compile(keyWord, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(title);
// 查找字符串中是否有匹配正则表达式的字符/字符串,并高亮替换
while(matcher.find()) {
String word = matcher.group();
String cssWord = BizConstants.Highlight_Font_LIFT + word + BizConstants.Highlight_Font_RIGHT;
title = title.replaceAll(word,cssWord);
}
}
return title;
}
}
###实践发现上述程序还是存在问题,会替换掉css代码本身,继续优化
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
public class FontUtils {
/**
* 高亮替换
*
* @param keyWord 关键词
* @param title 需替换的标题
* @return 返回结果字符串
*
*/
public static String cssTitle(String keyWord,String title) {
if(StringUtils.isNotEmpty(keyWord)) {
StringBuffer buffer = new StringBuffer();
getHighlightIndex(buffer,keyWord,title);
return buffer.toString();
}else {
return title;
}
}
//查找方法
private static void getHighlightIndex(StringBuffer buffer,String keyWord,String title) {
//不区分大小写,查找首次出现位置
int index = title.toUpperCase().indexOf(keyWord.toUpperCase());
if(index != -1) {
int cursorPoint = index + keyWord.length();
//截获前段,对截取片段替换
String startStr = title.substring(0, cursorPoint);
buffer.append(matcherStr(keyWord,startStr));
//获取遗留片段,继续处理
String endStr = title.substring(cursorPoint, title.length());
//System.err.println("endTitle="+endStr);
if(StringUtils.isNotEmpty(endStr)) {
getHighlightIndex(buffer,keyWord,endStr);
}
}else {
//没有匹配的直接组装返回
buffer.append(title);
}
}
//替换方法
private static String matcherStr(String keyWord,String wordStr) {
//不区分大小写
Pattern pattern = Pattern.compile(keyWord, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(wordStr);
// 查找字符串中是否有匹配正则表达式的字符/字符串,并高亮替换
while(matcher.find()) {
String word = matcher.group();
String cssWord = BizConstants.Highlight_Font_LIFT + word + BizConstants.Highlight_Font_RIGHT;
wordStr = wordStr.replaceAll(word,cssWord);
}
return wordStr;
}
// public static void main(String[] args) {
// System.out.println(FontUtils.cssTitle("t", "fgdTgftvvvfgg"));
// }
}