[英]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.