Android java get html image tag from string

I am trying to get the URL tag of an HTML image from a given string. There must be some regular expression to get it. But I don’t know how to do it. Can anyone help me on this.

eg.

I have string like this with <br> some HTML<b>tag</b> with <img src="http://xyz.com/par.jpg" align="left"/> image tags in it. how can get it ? 

I want only http://xyz.com/par.jpg from the string

+6
source share
4 answers

See this question for reference. It basically says:

 String imgRegex = "<img[^>]+src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>"; 
+7
source

I am using jsoup . It is quite easy to use and lightweight. Some versions were not compatible with Java 1.5, but it seems that they fixed the problem.

 String html = str; Document doc = Jsoup.parse(html); Elements pngs = doc.select("img[src$=.png]"); // img with src ending .png 
+3
source

Frist all jsoap imports:

 compile group: 'org.jsoup', name: 'jsoup', version: '1.7.2' 

Then you can use this:

 private ArrayList pullLinks(String html) { ArrayList links = new ArrayList(); Elements srcs = Jsoup.parse(html).select("[src]"); //get All tags containing "src" for (int i = 0; i < srcs.size(); i++) { links.add(srcs.get(i).attr("abs:src")); // get links of selected tags } return links; } 
+1
source

XMLPullParser can do this quite easily. Although, if this is a trivially small line, it may be redundant.

  XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); XmlPullParser xpp = factory.newPullParser(); xpp.setInput( new StringReader ( "<html>I have string like this with <br> some HTML<b>tag</b> with <img src=\"http://xyz.com/par.jpg\" align=\"left\"/> image tags in it. how can get it ?</html>" ) ); int eventType = xpp.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { if(eventType == XmlPullParser.START_TAG && "img".equals(xpp.getName()) { //found an image start tag, extract the attribute 'src' from here... } eventType = xpp.next(); } 
0
source

Source: https://habr.com/ru/post/894640/


All Articles