日期:2014-05-20  浏览次数:20678 次

如何使用正则添加img标签的max-width属性
原html样式字符串如下:
Java code

direct een antwoord! Of 'like'ons op Facebook en plaats uw vraag op ons Prikbord.&nbsp;</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"



如何替换下成下面的

Java code

direct een antwoord! Of 'like'ons op Facebook en plaats uw vraag op ons Prikbord.&nbsp;</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");
试试看吧。
------解决方案--------------------
Java code

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.&nbsp;</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.&nbsp;</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());
    }

}

------解决方案--------------------
(<img[^>]*style=\") 查找<img 开头的 然后可以是除>以外的任意字符的组合,也就是说可以使其他属性,比如src之类的,然后是style=“开头的,也就是你需要的,这里加上max-width="100%"就可以了