[英]How to get image source attribute value from img html tag in c#?
我的字符串变量存储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属性值?
以下代码将提取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);
您可以使用RegularExpressions
Regex("<img\\s+src\\s*=\\s*\"(.*?)\"", RegexOptions.Multiline);
结果:
第一组(索引0)-完全匹配
第二组(索引1)-组1-(。*?)-链接所需内容
在线测试正则表达式,您可以在这里
using System;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
string src = "";
Regex Pattern = new Regex("<img\\s+src\\s*=\\s*\"(.*?)\"", RegexOptions.Multiline);
string str = "<div> <img src=\"https://i.testimg.com/images/g/test/s-l400.jpg\" style=\"width: 100%;\"> <div>Test</div> </div>";
var res = Pattern.Match(str);
if (res.Success)
{
src = res.Groups[1].Value;
}
Console.WriteLine(src);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.