正则表达式获取图片地址和长宽高

前端之家收集整理的这篇文章主要介绍了正则表达式获取图片地址和长宽高前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

public static void main(String[] args) {
String str = "<p style='text-align: center;'><span class='marker'><strong>1104测试2</strong></span></p>"
+"<h2 style='font-style:italic;'>这是测是使用</h2>"
+"<p><img alt='' src='http://10.10.10.242:82/xxx/contracts/1478225023392_9c363621-5c13-4308-a77e-3206cb929153.jpg' style='height:220px; width:391px' /></p>"
+"<p>&nbsp;</p>"
+"<p>测试图片截取的</p>"
+"<p><img alt='' src='http://10.10.10.242:82/xxx/contracts/1478225059568_a73665bc-0909-4045-9c6d-4e8b8b0190c8.jpg' style='height:220px; width:293px' /></p>"
+"<p>&nbsp;</p>"
+"<p>图片3</p>"
+"<p><img alt='' src='http://10.10.10.242:82/xxx/contracts/1478225079772_c668f171-d5e5-4e98-aac2-98477a11d972.jpg' style='height:200px; width:200px' /></p>"
+"<p>&nbsp;</p>";

String regStr = "<img ([\\s\\S]*?) />"; //获取图片的 <img alt='' src='http://10.10.10.242:82/xxx/contracts/1478225079772_c668f171-d5e5-4e98-aac2-98477a11d972.jpg' style='height:200px; width:200px' />
String regUrl = "src='([\\s\\S]*?)'";
//style='height:200px; width:200px'
//String height = "style='height:([\\s\\S]*?)px;";
String height = "height:([\\s\\S]*?)px;";
String width = " width:([\\s\\S]*?)px'";

Pattern r = Pattern.compile(regStr);
Pattern u = Pattern.compile(regUrl);
Pattern h = Pattern.compile(height);
Pattern w = Pattern.compile(width);
Matcher m = r.matcher(str);


List<String> imgList = new ArrayList<String>();
while(m.find()){
String url = m.group(0) ;
Matcher mUrl = u.matcher(url);
Matcher hi = h.matcher(url);
Matcher wi = w.matcher(url);
String imgUrl = "";

while(mUrl.find()){
// System.out.println("Found value: " + mUrl.group(0) );
imgUrl = mUrl.group(0);
imgUrl = imgUrl.substring(5,imgUrl.length()-1);
}

String c = "0";
String k="0";
while(hi.find()){
// System.out.println("Found hi: " + hi.group(0) );
c= hi.group(0);
}

while(wi.find()){
//System.out.println("Found wi: " + wi.group(0) );
k=wi.group(0);
}
String cStr = "0";
String kStr = "0";
if(!"0".equals(c)){
cStr = c.substring(7,10);
}

if(!"0".equals(k)){
kStr = k.substring(7,10);
}

System.out.println("图片的长: "+cStr +" 宽:"+kStr+" 图片地址为:"+imgUrl);
}
/*if(m.find()){
for (int i = 0; i< m.groupCount();i++) {
System.out.println("Found value: " + m.group(i) );
}
while(m.find()){
System.out.println("Found value: " + m.group(0) );
}
}*/



}

效果

原文链接:https://www.f2er.com/regex/358833.html

猜你在找的正则表达式相关文章