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

本文介绍了一种将.doc文件转换为HTML的方法,并重点讲解了如何通过替换HTML标签来解决图片显示问题。此过程涉及到正则表达式匹配及字符串操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近的知识库系统项目需要对上传的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();

    }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值