Regular expression to find image url in <img> tag in HTML using VB.Net code

I want to extract the url of an image from any site. I am reading source information via webRequest. I need a regex that will extract the image url from this content, i.e. Src value in <img>

.

0


a source to share


3 answers


I would recommend using an HTML parser to read the html and pull the image tags out of it, as regexes don't converge well with data structures like xml and html.

In C #: ( from this SO question)



    var web = new HtmlWeb();
    var doc = web.Load("http://www.stackoverflow.com");

    var nodes = doc.DocumentNode.SelectNodes("//img[@src]");

    foreach (var node in nodes)
    {
            Console.WriteLine(node.src);
    }

      

+4


a source


Try it *:

<img .*?src=["']?([^'">]+)["']?.*?>

      

Tested here with:

<img class="test" src="/content/img/so/logo.png" alt="logo homepage">

      

gives

$1 = /content/img/so/logo.png

      



$ 1 (you have to hover over it to see it) matches the part of the regular expression between (). How you access this value will depend on which regex implementation you are using.

* If you want to know how it works, please leave a comment

EDIT As always with regex, there are cases of cross:

<img title="src=hack" src="/content/img/so/logo.png" alt="logo homepage">

      

This will correspond to a "hack".

+2


a source


/(?:\"|')[^\\x22*<>|\\\\]+?\.(?:jpg|bmp|gif|png)(?:\"|')/i 

      

is a decent one that I have used before. This gets any link to the image file in the html document. I haven't filmed the "or" around the match, so you'll need to do that.

+1


a source







All Articles