例如:
String data="<a href="#"><img src="https://i-vnexpress.vnecdn.net/2017/11/12/avangTp-1510462756-4342-1510462774_300x180.jpg"></a>akdjkasj<a href="#"><img src="https://i-vnexpress.vnecdn.net/2017/11/12/avantrumtiphchtch-1510458121-6358-1510458150_300x180.jpg"></a><a href="#"><img src="https://i-vnexpress.vnecdn.net/2017/11/12/23584171-515769268787265-1654747046-o-1510464027_680x0.jpg"></a>"
List<String> list=new ArrayList<>();
包含列表数据:{&#34; http://link 1&#34;,&#34; http://link 2&#34;,&#34; http://link 3&#34; } 如何替换src中的超链接:
data="<a href="#"><img src="http://link 1"></a>akdjkasj<a href="#"><img src="http://link 2"></a><a href="#"><img src="http://link 3"></a>"
我之后使用过代码:
public String replace(String str, List<String> arr){
Pattern pattern=Pattern.compile( "(?m)(?s)<img\\s+(.*)src\\s*=\\s*\"([^\"]+)\"(.*)" );
Matcher m=pattern.matcher(str);
StringBuffer sb=new StringBuffer();
int i=0;
while (m.find()){
String s1= m.group(0).replaceFirst(Pattern.quote(m.group(2)), list.get(i++));
m.appendReplacement(sb,s1);
}
m.appendTail(sb);
return sb.toString();
}
结果如下:
data="<a href="#"><img src="http://link 1"></a>akdjkasj<a href="#"><img src="https://i-vnexpress.vnecdn.net/2017/11/12/avantrumtiphchtch-1510458121-6358-1510458150_300x180.jpg"></a><a href="#"><img src="https://i-vnexpress.vnecdn.net/2017/11/12/23584171-515769268787265-1654747046-o-1510464027_680x0.jpg"></a>"
答案 0 :(得分:0)