加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 04:17:03 所属栏目:百科 来源:网络整理
导读:public static void main(String[] args) { String str = "p style='text-align: center;'span class='marker'strong1104测试2/strong/span/p" +"h2 style='font-style:italic;'这是测是使用/h2" +"pimg alt='' src='http://10.10.10.242:82/xxx/contracts/1

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 ([sS]*?) />"; //获取图片的 <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='([sS]*?)'";
//style='height:200px; width:200px'
//String height = "style='height:([sS]*?)px;";
String height = "height:([sS]*?)px;";
String width = " width:([sS]*?)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) );
}
}*/



}

效果:

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读