欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java获取图片的src值

程序员文章站 2022-04-13 14:09:24
...

使用正则,先获取到img 标签的内容,然后在匹配src

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.junit.Test;

public class T {

	@Test
	public void method(){
		String s = "<p><img src=\"/ueditor/jsp/upload/image/20180808/1533695526319046647.jpg\" _src=\"/ueditor/jsp/upload/image/20180808/1533695526319046647.jpg\" title=\"1533695526319046647.jpg\" alt=\"第5课.表达式[20180618-223635728].jpg\"/><img src=\"/ueditor/jsp/upload/image/20180808/1533695530256007298.jpg\" title=\"1533695530256007298.jpg\" alt=\"第5课.表达式[20180618-223639268].jpg\"/></p>";
		List<String> list = getSrc(s);
		System.out.println(list);
		
	}
	
	public List<String> getSrc(String s){
		//定义存储src内容的容器
		List<String> srcList = new ArrayList<String>();
		//获取img标签
		Pattern paImg = Pattern.compile("<(img|IMG)(.*?)(>|></img>|/>)");
		Matcher maImg = paImg.matcher(s);
		boolean flagImg = maImg.find();
		//循环检测img标签
		while(flagImg){
			//获取到img标签内容
			String img = maImg.group(2);
			//匹配src
			Pattern paSrc = Pattern.compile("(src|SRC)=(\"|\')(.*?)(\"|\')");
			//获取到src标签内容
			Matcher maSrc = paSrc.matcher(img);
			if(maSrc.find()){
				//将src内容放入容器
				srcList.add( maSrc.group(3) );
			}
			//循环条件,判断img标签
			flagImg = maImg.find();
		}
				
		return srcList;
	}
}

转载https://blog.csdn.net/u013350866/article/details/79035824

相关标签: 图片