/**
* 拆分html的内容,把xxxxx<a>xxxxx</a>xxxx这样格式的内容拆分开来
* @param html 要解析的html文档内容
* @return
*/
public static InfoSplitBean getHTMLContext(String html, String keyword, String url){
//<a href="javascript:;">jvldsjf面试官ljsdlfkm</a>
Pattern p = Pattern.compile("<a.*?>.*?(</a>){1}?");//匹配<a>开头
//获取非a标签那块内容
String[] split = p.split(html);
Matcher m = p.matcher(html);//寻找a标签的内容
//得到a标签里面那块内容
List<String> aLabelList = new ArrayList<String>();
Stack<String> aLabelStack = new Stack<String>();
while (m.find()) {
aLabelList.add(m.group());
}
//倒序入栈
Collections.reverse(aLabelList);
for(String s : aLabelList){
aLabelStack.push(s);
}
//寻找需要替换的位置,和替换内容
List<String> tmpList = new ArrayList<String>();
boolean hasReplace = false;
//拆分的时候,可能会有空的
for(String s : split){
int idx = s.indexOf(keyword);
if(!hasReplace && idx > -1){
tmpList.add(s.replaceFirst(keyword, "<a href=\""+url+"\" target=\"_blank\">"+keyword+"</a>"));
hasReplace = true;
}else{
tmpList.add(s);
}
}
//倒序入栈
Stack<String> splitStack = new Stack<String>();
for(int i=tmpList.size()-1;i>-1;i--){
splitStack.push(tmpList.get(i));
}
StringBuffer sb = new StringBuffer();
//匹配内容,考虑每次替换之后,长度会改变。
while(!splitStack.isEmpty() || !aLabelStack.isEmpty()){
sb.append(!splitStack.isEmpty()?splitStack.peek():"").append(!aLabelStack.isEmpty()?aLabelStack.peek():"");
if(!splitStack.isEmpty()){
splitStack.pop();
}
if(!aLabelStack.isEmpty()){
aLabelStack.pop();
}
}
InfoSplitBean infoSplitBean = new InfoSplitBean();
infoSplitBean.setSuccess(hasReplace);
infoSplitBean.setContext(sb.toString());
return infoSplitBean;
}
代码优化
/**
* @see {@link InfoAction getHTMLContext()}
* @param html
* @param keyword
* @param url
* @return
*/
public static JSONObject getHTMLContextOptimum(String html, String keyword, String url){
JSONObject jsonObject = new JSONObject();
String result = html.replaceFirst("(?i)"+keyword+"(?=[^<>]*(?:<\\w|<\\/[^a]|$))", "<a href=\""+url+"\" target=\"_blank\">"+keyword+"</a>");
if (result.length() - html.length() > 0) {
jsonObject.put("success", true);
}else{
jsonObject.put("success", false);
}
jsonObject.put("result", result);
return jsonObject;
}