java android java从字符串中获取html图像标签

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6998163/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 18:12:01  来源:igfitidea点击:

android java get html image tag from string

javaandroidhtmlstring

提问by Umakant Patil

Im trying to get HTML image tag url from the given string. There should be some regular expression to get it. But don't know how to do it. Can anyone help me on this.

我试图从给定的字符串中获取 HTML 图像标记 url。应该有一些正则表达式来获取它。但是不知道怎么做。谁可以帮我这个事。

e.g.

例如

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.jpgfrom the string

我只想要字符串中的http://xyz.com/par.jpg

采纳答案by Hyman

Please see thisquestion for reference. Basically it says to use:

请参阅问题以供参考。基本上它说使用:

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

回答by Frohnzie

I use jsoup. It is pretty easy to use and lightweight. Some versions were not Java 1.5 compatible but it appears they fixed the issue.

我使用jsoup。它非常易于使用且重量轻。有些版本与 Java 1.5 不兼容,但似乎他们解决了这个问题。

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

回答by Mahdi Astanei

Frist of All Import jsoap:

导入 jsoap 之首:

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;
}

回答by nicholas.hauschild

An XMLPullParsercan do this pretty easily. Although, if it is a trivially small string, it may be overkill.

一个XMLPullParser可以做到这一点很容易地。虽然,如果它是一个微不足道的小字符串,它可能会矫枉过正。

     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();
     }