当前位置: 移动技术网 > IT编程>开发语言>Java > java正则替换img标签中src值的方法

java正则替换img标签中src值的方法

2019年07月19日  | 移动技术网IT编程  | 我要评论

主要功能是: 替换html字符串中img标签src的值.

代码如下:

package com.junlenet.common.util;
import java.util.regex.matcher;
import java.util.regex.pattern;
/**
 * html处理工具类
 * @author huweijun
 * @date 2016年7月13日 下午7:25:09
 */
public class htmlutils {
	/**
	 * 替换指定标签的属性和值
	 * @param str 需要处理的字符串
	 * @param tag 标签名称
	 * @param tagattrib 要替换的标签属性值
	 * @param starttag 新标签开始标记
	 * @param endtag 新标签结束标记
	 * @return
	 * @author huweijun
	 * @date 2016年7月13日 下午7:15:32
	 */
	public static string replacehtmltag(string str, string tag, string tagattrib, string starttag, string endtag) {
		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);
  		matcherforattrib.appendreplacement(sbreplace, starttag + attributestr + endtag);
  	}
  	matcherforattrib.appendtail(sbreplace);
  	matcherfortag.appendreplacement(sb, sbreplace.tostring());
  	result = matcherfortag.find();
		}
		matcherfortag.appendtail(sb);   
		return sb.tostring();
	}
 
 public static void main(string[] args) {
 	stringbuffer content = new stringbuffer();
 	content.append("<ul class=\"imgbox\"><li><img id=\"160424\" src=\"uploads/allimg/160424/1-160424120t1-50.jpg\" class=\"src_class\"></li>");
 	content.append("<li><img id=\"150628\" src=\"uploads/allimg/150628/1-15062q12247.jpg\" class=\"src_class\"></li></ul>");
  system.out.println("原始字符串为:"+content.tostring());
  string newstr = replacehtmltag(content.tostring(), "img", "src", "src=\"http://junlenet.com/", "\"");
  system.out.println("  替换后为:"+newstr);
 } 
 
}

以上这篇java正则替换img标签中src值的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网