2011-08-09 10 views
6

Próbuję uzyskać URL tagu obrazu HTML z podanego ciągu. Powinno być jakieś regularne wyrażenie, aby je zdobyć. Ale nie wiem, jak to zrobić. Czy ktokolwiek może mi z tym pomóc.Android java uzyskać tag obrazu HTML ze stringów

np.

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 ? 

Chcę tylko http://xyz.com/par.jpg z łańcucha

Odpowiedz

7

proszę zobaczyć this pytanie do odniesienia. Zasadniczo mówi się użyć:

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

An XMLPullParser może to zrobić całkiem łatwo. Chociaż, jeśli jest to banalnie mały ciąg, może to być przesada.

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

Używam jsoup. Jest łatwy w użyciu i lekki. Niektóre wersje nie były zgodne z Java 1.5, ale wydaje się, że naprawiły problem.

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

Frist wszystkich import jsoap:

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

następnie można użyć to:

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