不少项目都须要到富文原本添加内容,就比如新闻啊,旅游景点之类的,都须要使用富文本去添加数据,然而怎么我这边就发现了两个问题html
怎样将富文本的图片的 src 获取出来?正则表达式
方法一:工具
利用正则表达式:spa
public static List<String> getImgStr(String htmlStr) { List<String> list = new ArrayList<>(); String img = ""; Pattern p_image; Matcher m_image; // String regEx_img = "<img.*src=(.*?)[^>]*?>"; //图片连接地址 String regEx_img = "<img.*src\\s*=\\s*(.*?)[^>]*?>"; p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE); m_image = p_image.matcher(htmlStr); while (m_image.find()) { // 获得<img />数据 img = m_image.group(); // 匹配<img>中的src数据 Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img); while (m.find()) { list.add(m.group(1)); } } return list; }
便可获取到如下结果3d
方法二:code
引入一个叫作 jsoup 的 jar, (下载地址:https://jsoup.org/download)htm
<dependency> <groupId>org.jsoup</groupId> <artifactId>jsoup</artifactId> <version>1.11.2</version> </dependency>
下面是工具类blog
public static String documentBody (String newsBody) { Element doc = Jsoup.parseBodyFragment(newsBody).body(); Elements pngs = doc.select("img[src]"); String httpHost = "http://192.168.0.100"; for (Element element : pngs) { String imgUrl = element.attr("src"); if (imgUrl.trim().startsWith("/")) { // 会去匹配咱们富文本的图片的 src 的相对路径的首个字符,请注意一下 imgUrl =httpHost + imgUrl; element.attr("src", imgUrl); } } return newsBody = doc.toString(); }
转载自:https://www.cnblogs.com/xjbBill/p/8439248.html图片