简体   繁体   English

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

[英]How to get image source attribute value from img html tag in c#?

My string variable stores set of HTML Tags along with img source file link. 我的字符串变量存储HTML标签集以及img源文件链接。

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

How to get the src attribute value from the string str. 如何从字符串str获取src属性值。 Apparently, i will have to assign the value of src to another variable. 显然,我将不得不将src的值分配给另一个变量。

How to get src attribute value from img html tag in c#? 如何从C#中的img html标签获取src属性值?

The following code will extract the value of the src attribute. 以下代码将提取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);

You can use RegularExpressions 您可以使用RegularExpressions

Regex("<img\\s+src\\s*=\\s*\"(.*?)\"", RegexOptions.Multiline);

in results: 结果:
first group (index 0) - Full match 第一组(索引0)-完全匹配
second group (index 1) - group 1 - (.*?) - link what you want 第二组(索引1)-组1-(。*?)-链接所需内容

test regex online you can here 在线测试正则表达式,您可以在这里

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM