要使用 C# 正则表达式获取 HTML 中图片标签的 src 属性,你可以尝试以下方法:
假设你有一个包含 HTML 内容的字符串 htmlContent,你可以使用正则表达式来提取其中的图片 src 属性值。
- using System;
- using System.Text.RegularExpressions;
-
- class Program
- {
- static void Main()
- {
- string htmlContent = "<img src='image1.jpg' alt='Image 1'><img src='image2.jpg' alt='Image 2'>";
-
- string pattern = @"<img[^>]*?src\s*=\s*['""]?(?<src>[^'"">]+)['""]?[^>]*>";
-
- MatchCollection matches = Regex.Matches(htmlContent, pattern);
-
- foreach (Match match in matches)
- {
- Group srcGroup = match.Groups["src"];
- string srcValue = srcGroup.Value;
- Console.WriteLine($"Image src: {srcValue}");
- }
- }
- }
-
这段代码中的正则表达式 pattern 用于匹配 HTML 中的 img 标签,并提取其中的 src 属性值。然后通过 Regex.Matches() 方法获取所有匹配项,遍历每个匹配项并提取 src 属性值。
请注意,使用正则表达式来解析 HTML 有其局限性,并且不推荐对复杂的 HTML 结构使用正则表达式。在实际项目中,更好的方法是使用 HTML 解析器(比如 HtmlAgilityPack)来处理 HTML 内容,以提取其中的特定元素及其属性。