java 替换富文本中照片的域名地址

3 篇文章 0 订阅
2 篇文章 0 订阅
/**
 * 替换指定标签的属性和值
 * @param str 需要处理的字符串
 * @param tag 标签名称
 * @param tagAttrib 要替换的标签属性值
 * @param startTag 新标签开始标记
 * @param endTag 新标签结束标记
 */
public static String replaceImgSrc(String str, String tag, String tagAttrib, String startTag, String endTag) throws MalformedURLException {
    String regxpForTag = "<\\s*" + tag + "\\s+([^>]*)\\s*" ;
    String regxpForTagAttrib = tagAttrib + "=\\s*\"([^\"]+)\"" ;
    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();
    while (result) {
        StringBuffer sbreplace = new StringBuffer( "<"+tag+" ");
        Matcher matcherForAttrib = patternForAttrib.matcher(matcherForTag.group(1));
        if (matcherForAttrib.find()) {
            String attributeStr = matcherForAttrib.group(1);

            URL url=new URL(attributeStr.trim());
            matcherForAttrib.appendReplacement(sbreplace, startTag + url.getPath() + endTag);
        }
        matcherForAttrib.appendTail(sbreplace);
        matcherForTag.appendReplacement(sb, sbreplace.toString());
        result = matcherForTag.find();
    }
    matcherForTag.appendTail(sb);
    return sb.toString();
}
public static void main(String[] args) throws MalformedURLException {
    StringBuffer content = new StringBuffer();
    content.append("<ul class=\"imgBox\"><li><img id=\"160424\" src=\"https://ww.com/uploads/allimg/160424/1-160424120T1-50.jpg\" class=\"src_class\"></li>");
    content.append("<li><img id=\"150628\" src=\"https://ww.com/uploads/allimg/150628/1-15062Q12247.jpg\" class=\"src_class\"></li></ul>");
    System.out.println("原始字符串为:"+content.toString());
    String newStr = replaceImgSrc(content.toString(), "img", "src", "src=\"http://junlenet.com/", "\"");
    System.out.println("  替换后为:"+newStr);
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值