Java正则表达式替换Img标签的src属性

最近的知识库系统项目需要对上传的doc文件转为html,然后在kindeditor中编辑,由于图片显示不出来,故需要修改img的src属性

    /**

      *

      * 基本功能:替换指定的标签

      * @author linshutao

      * @param str

      * @param beforeTag   要替换的标签

      * @param tagAttrib   要替换的标签属性值

      * @param startTag    新标签开始标记

      * @param endTag   新标签结束标记

      * @return String

      */

    public   static String replaceHtmlTag(String str, String beforeTag,

       String tagAttrib, String startTag, String endTag) {

    //  String regxpForTag = "<//s*" + beforeTag + "//s+([^>]*)//s*>" ;

    String regxpForTag = "<//s*" + beforeTag + "//s+([^>]*)//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 = new StringBuffer ();

       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();

    }

你可能感兴趣的:(java,html,String,正则表达式)