如何从c#中的img html标签获取图像源属性值?

我的字符串变量存储 HTML 标签集以及 img 源文件链接。

string str = "<div> <img src="https://i.testimg.com/images/g/test/s-l400.jpg" style="width: 100%;"> <div>Test</div> </div>"

如何从字符串str中获取src属性值。显然,我必须将 src 的值分配给另一个变量。

如何从c#中的img html标签获取src属性值?


holdtom
浏览 141回答 2
2回答

隔江千里

以下代码将提取属性的值src。string str = "<div> <img src=\"https://i.testimg.com/images/g/test/s-l400.jpg\" style=\"width: 100%;\"> <div>Test</div> </div>";// Get the index of where the value of src starts.int start = str.IndexOf("<img src=\"") + 10;// Get the substring that starts at start, and goes up to first \".string src = str.Substring(start, str.IndexOf("\"", start) - start);

繁星点点滴滴

您可以使用正则表达式Regex("<img\\s+src\\s*=\\s*\"(.*?)\"",&nbsp;RegexOptions.Multiline);在结果中:第一组(索引 0) - 完全匹配第二组(索引 1) - 组 1 - (.*?) - 链接你想要的内容在线测试正则表达式你可以在这里using System;using System.Text.RegularExpressions;public class Program{&nbsp; &nbsp; public static void Main()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; string src = "";&nbsp; &nbsp; &nbsp; &nbsp; Regex Pattern = new Regex("<img\\s+src\\s*=\\s*\"(.*?)\"", RegexOptions.Multiline);&nbsp; &nbsp; &nbsp; &nbsp; string str = "<div> <img src=\"https://i.testimg.com/images/g/test/s-l400.jpg\" style=\"width: 100%;\"> <div>Test</div> </div>";&nbsp; &nbsp; &nbsp; &nbsp; var res = Pattern.Match(str);&nbsp; &nbsp; &nbsp; &nbsp; if (res.Success)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; src = res.Groups[1].Value;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine(src);&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP