Java正则表达式替换Img标签的src属性
最近的知识库系统项目需要对上传的doc文件转为html,然后在kindeditor中编辑,由于图片显示不出来,故需要修改img的src属性/****基本功能:替换指定的标签
*@authorlinshutao
*@paramstr
*@parambeforeTag要替换的标签
*@paramtagAttrib要替换的标签属性值
*@paramstartTag新标签开始标记
*@paramendTag新标签结束标记
*@returnString
*/
publicstaticStringreplaceHtmlTag(Stringstr,StringbeforeTag,
StringtagAttrib,StringstartTag,StringendTag){
//StringregxpForTag="]*)\\s*>";
StringregxpForTag="]*)\\s*";
StringregxpForTagAttrib=tagAttrib+"=\\s*\"([^\"]+)\"";
//Pattern.CASE_INSENSITIVE忽略大小写PatternpatternForTag=Pattern.compile(regxpForTag,Pattern.CASE_INSENSITIVE);PatternpatternForAttrib=Pattern.compile(regxpForTagAttrib,Pattern.CASE_INSENSITIVE);MatchermatcherForTag=patternForTag.matcher(str);StringBuffersb=newStringBuffer();booleanresult=matcherForTag.find();//循环找出每个img标签
while(result){
StringBuffersbreplace=newStringBuffer("<img");
MatchermatcherForAttrib=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);
returnsb.toString();
}