My string variable stores set of HTML Tags along with img source file link.
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. Apparently, i will have to assign the value of src to another variable.
How to get src attribute value from img html tag in c#?
The following code will extract the value of the src
attribute.
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
Regex("<img\\s+src\\s*=\\s*\"(.*?)\"", RegexOptions.Multiline);
in results:
first group (index 0) - Full match
second group (index 1) - group 1 - (.*?) - link what you want
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);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.