原html样式字符串如下:
direct een antwoord! Of 'like'ons op Facebook en plaats uw vraag op ons Prikbord. </div>
<div><img alt="" style="width: 560px; height: 310px; src="/Upload/sys/twitter_facebook%20spreekuur.jpg" /><br />
</div>
<div data-font="lucida grande" data-show-faces="false" data-width="450" data-send="true"
如何替换下成下面的
direct een antwoord! Of 'like'ons op Facebook en plaats uw vraag op ons Prikbord. </div>
<div><img alt="" style="max-width:100%; width: 560px; height: 310px; " src="/Upload/sys/twitter_facebook%20spreekuur.jpg" /><br />
</div>
<div data-font="lucida grande" data-show-faces="false" data-width="450" data-send="true"
诸位朋友会发现只是在img的内部style属性里添加了max-width=100%;谢谢各位了!
direct een antwoord! Of 'like'ons op Facebook en plaats uw vraag op ons Prikbord. </div>
<div><img alt="" style="width: 560px; height: 310px; src="/Upload/sys/twitter_facebook%20spreekuur.jpg" /><br />
</div>
<div data-font="lucida grande" data-show-faces="false" data-width="450" data-send="true"
如何替换下成下面的
direct een antwoord! Of 'like'ons op Facebook en plaats uw vraag op ons Prikbord. </div>
<div><img alt="" style="max-width:100%; width: 560px; height: 310px; " src="/Upload/sys/twitter_facebook%20spreekuur.jpg" /><br />
</div>
<div data-font="lucida grande" data-show-faces="false" data-width="450" data-send="true"
诸位朋友会发现只是在img的内部style属性里添加了max-width=100%;谢谢各位了!
<img alt="" style="width:往中间插入max-width:100%;
str = str.replaceAll("(?s)(<Image[^>]*?style=\")(width:)","$1max-width:100%;$2");
试试看吧。
Pattern p = Pattern.compile("(.*?<img.*?style=\")(.*?)(\".*)");
Matcher m =p.matcher(str);
String result=m.replaceAll("$1 max-wdth:100%; $2$3");
System.out.println(result);
多谢了,不过这个只能适用于只有一个img标签的情况,假如有两个或者两个以上应该就不成立了,不过还是表示感谢,再等等,有没有更好的方法。谢谢。
public class Regex {
public static void main(String[] args) {
String str = "direct een antwoord! Of 'like'ons op Facebook en plaats uw vraag op ons Prikbord. </div>"
+"<div><img alt=\"\" style=\"width: 560px; height: 310px; src=\"/Upload/sys/twitter_facebook%20spreekuur.jpg\" /><br />"
+"</div>"
+"<div data-font=\"lucida grande\" data-show-faces=\"false\" data-width=\"450\" data-send=\"true\""
+ "direct een antwoord! Of 'like'ons op Facebook en plaats uw vraag op ons Prikbord. </div>"
+"<div><img alt=\"\" style=\"width: 560px; height: 310px; src=\"/Upload/sys/twitter_facebook%20spreekuur.jpg\" /><br />"
+"</div>"
+"<div data-font=\"lucida grande\" data-show-faces=\"false\" data-width=\"450\" data-send=\"true\"";
Pattern p = Pattern.compile("(<img[^>]*style=\")");
Matcher m =p.matcher(str);
StringBuffer sb = new StringBuffer();
while(m.find()){
m.appendReplacement(sb, "$1max-width:100%; ");
}
m.appendTail(sb);
System.out.println(sb.toString());
}}