700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > html字符串替换src 替换html字符串中img标签src的值.

html字符串替换src 替换html字符串中img标签src的值.

时间:2020-05-07 23:03:48

相关推荐

html字符串替换src 替换html字符串中img标签src的值.

mon.util;importjava.util.regex.Matcher;importjava.util.regex.Pattern;/*** html处理工具类

*@authorhuweijun

* @date 7月13日 下午7:25:09*/

public classHtmlUtils {/*** 替换指定标签的属性和值

*@paramstr 需要处理的字符串

*@paramtag 标签名称

*@paramtagAttrib 要替换的标签属性值

*@paramstartTag 新标签开始标记

*@paramendTag 新标签结束标记

*@return*@authorhuweijun

* @date 7月13日 下午7:15:32*/

public staticString replaceHtmlTag(String str, String tag, String tagAttrib, String startTag, String endTag) {

String regxpForTag= "]*)\s*";

String regxpForTagAttrib= tagAttrib + "=\s*"([^"]+)"";

Pattern patternForTag=pile (regxpForTag,Pattern. CASE_INSENSITIVE );

Pattern patternForAttrib=pile (regxpForTagAttrib,Pattern. CASE_INSENSITIVE );

Matcher matcherForTag=patternForTag.matcher(str);

StringBuffer sb= newStringBuffer();boolean result =matcherForTag.find();while(result) {

StringBuffer sbreplace= new StringBuffer( "

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);returnsb.toString();

}public static voidmain(String[] args) {

StringBuffer content= newStringBuffer();

content.append("

");

content.append("

");

System.out.println("原始字符串为:"+content.toString());

String newStr= replaceHtmlTag(content.toString(), "img", "src", "src="/", """);

System.out.println(" 替换后为:"+newStr);

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。