One of the most recent projects on Web page drawing is my own development, which is to use regular expressions to match the image tags.
In general, an HTML document has a lot of tags, such as "
We can think of how to build this regular expression from the HTML tag format. The first thing to think about the IMG tags are several ways to write, ignoring the case, the following list of possible IMG tags can occur.
These tags do not need to be considered, because there is no picture resource address.
Some of these tags have a picture resource address, and another feature is a quotation mark pair, which may be single or double quotation marks. Because there is no need to match the quotes pair at the same time, the regular expression can be written like this: @ "]*) \s*/?\s*> "
Because there may be other parameters between IMG and SRC, so "]*?\bsrc\s*=\s*[" "']?\s*" (? [ ^\s "" ' <>]*) [^<>]*?/?\s*> "
/images/pic.jpg "/>
Problems such as the possibility of folding the line with a carriage return sometimes occur, so include a carriage return line and tab character where there are spaces, and no spaces, tabs, carriage returns, or newline characters in the image address. So the above regular expression can be changed to: @ "]*?\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 that gets all the image addresses in the HTML.
- <summary>
- /// Get the URL of all pictures in HTML.
- // </summary>
- /// <param name= "Shtmltext" >html code </param>
- /// <returns> URL List of images </returns>
- public static string[] Gethtmlimageurllist (string shtmltext)
- {
- //define regular expressions to match an 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 matching strings
- MatchCollection matches = regimg.matches (Shtmltext);
- int i = 0;
- string[] surllist = new string[matches. Count];
- //Get a list of matches
- foreach (Match match in matches)
- surllist[i++] = match. groups["Imgurl"]. Value;
- return surllist;
- }
C # Regular expression matches the picture path in HTML