How can I use regular expression to grab an 'img' tag?

前端 未结 3 1176
难免孤独
难免孤独 2020-12-06 10:04

I want to grab an img tag from text returned from JSON data like that. I want to grab this from a string:



        
相关标签:
3条回答
  • 2020-12-06 10:26

    Please note you shouldn't use regular expressions to parse HTML for the various reasons

    <img\s+[^>]*src="([^"]*)"[^>]*>
    

    Or use Jsoup...

    String html = "<img class=\"img\" src=\"https://fbcdn-photos-c-a.akamaihd.net/
                   hphotos-ak-frc3/1239478_598075296936250_1910331324_s.jpg\" alt=\"\" />";
    
    Document doc = Jsoup.parse(html);
    Element img = doc.select("img").first();
    String src = img.attr("src");
    
    System.out.println(src);
    
    0 讨论(0)
  • 2020-12-06 10:29

    Your regex doesn't match the string, because it's missing the closing /.

    Edit - No, the / is not necessary, so your regex should have worked. But you can relax it a bit like below.

    Slightly modified:

     <img\s[^>]*?src\s*=\s*['\"]([^'\"]*?)['\"][^>]*?>
    
    0 讨论(0)
  • 2020-12-06 10:31

    You could simply use this expression to match an img tag as in the example :

    <img([\w\W]+?)/>
    
    0 讨论(0)
提交回复
热议问题