为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C#
holdtom 2023-07-09 10:19:43
我的字符串变量存储 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属性值?
查看完整描述

2 回答

?
隔江千里

TA贡献1906条经验 获得超10个赞

以下代码将提取属性的值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);


查看完整回答
反对 回复 2023-07-09
?
繁星点点滴滴

TA贡献1803条经验 获得超3个赞

您可以使用正则表达式

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);

    }

}


查看完整回答
反对 回复 2023-07-09
  • 2 回答
  • 0 关注
  • 77 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信