最近的知识库系统项目需要对上传的doc文件转为html,然后在kindeditor中编辑,由于图片显示不出来,故需要修改img的src属性 /** * *基本功能:替换指定的标签
*@authorlinshutao
*@paramstr
*@parambeforeTag 要替换的标签
*@paramtagAttrib 要替换的标签属性值
*@paramstartTag 新标签开始标记
*@paramendTag 新标签结束标记
*@returnString
*/
public static String replaceHtmlTag(String str, String beforeTag,
String tagAttrib, String startTag, String endTag) {
// String regxpForTag = "]*)\\s*>";
String regxpForTag = "]*)\\s*";
String regxpForTagAttrib = tagAttrib + "=\\s*\"([^\"]+)\"";
//Pattern.CASE_INSENSITIVE 忽略大小写 Pattern patternForTag = Pattern.compile (regxpForTag,Pattern.CASE_INSENSITIVE); Pattern patternForAttrib = Pattern.compile (regxpForTagAttrib,Pattern.CASE_INSENSITIVE); Matcher matcherForTag = patternForTag.matcher(str); StringBuffer sb = newStringBuffer(); boolean result = matcherForTag.find(); //循环找出每个img标签
while (result) {
StringBuffer sbreplace = new StringBuffer("<img ");
Matcher matcherForAttrib = patternForAttrib.matcher(matcherForTag
.group(1));
if (matcherForAttrib.find()) {
matcherForAttrib.appendReplacement(sbreplace, startTag
+ matcherForAttrib.group(1) + endTag);
}
matcherForAttrib.appendTail(sbreplace);
matcherForTag.appendReplacement(sb, sbreplace.toString());
result = matcherForTag.find();
}
matcherForTag.appendTail(sb);
return sb.toString();
}
*@authorlinshutao
*@paramstr
*@parambeforeTag 要替换的标签
*@paramtagAttrib 要替换的标签属性值
*@paramstartTag 新标签开始标记
*@paramendTag 新标签结束标记
*@returnString
*/
public static String replaceHtmlTag(String str, String beforeTag,
String tagAttrib, String startTag, String endTag) {
// String regxpForTag = "]*)\\s*>";
String regxpForTag = "]*)\\s*";
String regxpForTagAttrib = tagAttrib + "=\\s*\"([^\"]+)\"";
//Pattern.CASE_INSENSITIVE 忽略大小写 Pattern patternForTag = Pattern.compile (regxpForTag,Pattern.CASE_INSENSITIVE); Pattern patternForAttrib = Pattern.compile (regxpForTagAttrib,Pattern.CASE_INSENSITIVE); Matcher matcherForTag = patternForTag.matcher(str); StringBuffer sb = newStringBuffer(); boolean result = matcherForTag.find(); //循环找出每个img标签
while (result) {
StringBuffer sbreplace = new StringBuffer("<img ");
Matcher matcherForAttrib = patternForAttrib.matcher(matcherForTag
.group(1));
if (matcherForAttrib.find()) {
matcherForAttrib.appendReplacement(sbreplace, startTag
+ matcherForAttrib.group(1) + endTag);
}
matcherForAttrib.appendTail(sbreplace);
matcherForTag.appendReplacement(sb, sbreplace.toString());
result = matcherForTag.find();
}
matcherForTag.appendTail(sb);
return sb.toString();
}