Generally, an HTML document has many tags, such as <HTML>, <body>, and <Table>, it is not easy to extract the IMG tags in the document. Because the IMG label style is changeable, it is not easy to use programs to search for it during extraction. Therefore, if you want to search for them, you must write a sound regular expression. Otherwise, you may not be able to find them completely or find the correct IMG tag.
We can think about how to create this regular expression from the HTML tag format. First, I want to write several methods for IMG labels. If I ignore case sensitivity, I will list several possible causes of IMG labels.
You do not need to consider these labels because there is no image resource address.
These tags all have image resource addresses. In addition, they have pair quotation marks, which may be single or double quotation marks. Because quotation marks do not need to be matched at the same time, the regular expression can be written as follows: @ "] *) \ s */? \ S *>"
Because there may be other parameters between IMG and SRC, "] *? \ Bsrc \ s * = \ s * ["" ']? \ S *(? [^ \ s "" '<>] *) [^ <>] *? /? \ S *>"
/Images/pic.jpg "/>
For example, a carriage return or line break may occur. Therefore, a line break or Tab character must be included in a separate space, in addition, space, tab, carriage return, and line feed characters cannot appear in the image address. So the above regular expression can be changed :@"] *? \ Bsrc [\ s \ t \ r \ n] * = [\ s \ t \ r \ n] * ["']? [\ S \ t \ r \ n] * (? [^ \ s \ t \ r \ n "" '<>] *) [^ <>] *? /? [\ S \ t \ r \ n] *>"
The following is a static method for getting all the image addresses in HTML.
/// <Summary>
/// Obtain the URLs of all images in HTML.
/// </Summary>
/// <Param name = "shtmltext"> HTML code </param>
/// <Returns> List of image URLs </returns>
Public static string [] gethtmlimageurllist (string shtmltext)
{
// Define a regular expression to match the IMG tag
RegEx regimg = new RegEx (@ "] *? \ Bsrc [\ s \ t \ r \ n] * = [\ s \ t \ r \ n] * ["']? [\ S \ t \ r \ n] * (? [^ \ s \ t \ r \ n "" '<>] *) [^ <>] *? /? [\ S \ t \ r \ n] *> ", regexoptions. ignorecase );
// Search for matched strings
Matchcollection matches = regimg. Matches (shtmltext );
Int I = 0;
String [] surllist = new string [matches. Count];
// Obtain the matching item list
Foreach (match in matches)
Surllist [I ++] = match. Groups ["imgurl"]. value;
Return surllist;
}