Extract image tags from HTML in C#

February 25, 2010 C# Regular expressions Nils Snippet
A pretty little C# function that returns a list of strings containing all image tags extracted from a HTML string.
private List<string> GetImagesInHTMLString(string htmlString) {
List<string> images = new List<string>();
string pattern = @"<(img)\b[^>]*>";

Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);
MatchCollection matches = rgx.Matches(htmlString);

for(int i=0, l=matches.Count; i<l; i++) {
images.Add(matches[i].Value);
}

return images;
}

Related posts: