java regular replacement of src value in img tag

The main function is: replace the value of the img tag src in the html string.

code show as below:     

    

package com.junlenet.common.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * html processing tool class
 * @author huweijun
 *@date July 13, 2016 at 7:25:09 PM
 */
public class HtmlUtils {

	/**
	 * Replace the attributes and values ​​of the specified tag
	 * @param str String to be processed
	 * @param tag tag name
	 * @param tagAttrib the tag attribute value to replace
	 * @param startTag new tag start tag
	 * @param endTag new tag end tag
	 * @return
	 * @author huweijun
	 *@date Jul 13, 2016 at 7:15:32 PM
	 */
	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 );   
		Matches matchesForTag = patternForTag.matches (size);
		StringBuffer sb = new StringBuffer();
		boolean result = matcherForTag.find();
		while (result) {
			StringBuffer sbreplace = new StringBuffer( "<"+tag+" ");
		    Matches matchesForAttrib = patternForAttrib.matches (matchesForTag.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("The original string is: "+content.toString());
        String newStr = replaceHtmlTag(content.toString(), "img", "src", "src=\"http://junlenet.com/", "\"");
        System.out.println(" Replaced with: "+newStr);
    }
    
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326045721&siteId=291194637