0

I use asp.net project in server side.

I have this string: <img src="../../SpatialData/sometext/813.jpg" style="width:190px">

at some point I need to extruct src from string:

../../SpatialData/sometext/813.jpg  

How can I get substring using c#?

Michael
  • 13,950
  • 57
  • 145
  • 288
  • 1
    may be worth checking out this if you're able to use it and this problem isn't a one time thing. Makes extracting that info easier. http://html-agility-pack.net/ – parameter Aug 22 '18 at 12:13
  • https://stackoverflow.com/questions/1512562/parsing-html-page-with-htmlagilitypack or https://stackoverflow.com/questions/56107/what-is-the-best-way-to-parse-html-in-c etc etc.. The real question is : **Do you need a Html parser or it's a one time job on a simple string?** – Drag and Drop Aug 22 '18 at 12:23
  • Possible duplicate of [only get the src value](https://stackoverflow.com/questions/18330460/only-get-the-src-value) – Drag and Drop Aug 22 '18 at 12:27
  • duplicate: https://stackoverflow.com/questions/4835868/how-to-get-img-src-or-a-hrefs-using-html-agility-pack .. man to mutch good post about it. any Google 'C# get img src' will give you result. – Drag and Drop Aug 22 '18 at 12:29

1 Answers1

0

You can use some regex to solve that...

var test = "<img src=\"../../SpatialData/sometext/813.jpg\" style=\"width:190px\">";

var pattern = @"<img src=""([^\""]*)";

var result = Regex.Match(test, pattern).Groups[1].Value;

Console.WriteLine(result);

The issue is... if you're performing that function against any html document with multiple image tags, it's not going to work, to get them all...

test = "<img src=\"../../SpatialData/sometext/813.jpg\" style=\"width:190px\"><img src=\"../../SpatialData/sometext/814.jpg\" style=\"width:190px\">";

var matches = Regex.Matches(test, pattern)
                   .Cast<Match>()
                   .Select(x=>x.Groups[1].Value);

foreach (var m in matches)
{
    Console.WriteLine(m);
}

As someone has already stated, HTML agility pack is an option worth looking into, the solution I've provided above is very rigid, if the attributes on the image tag were to be reordered differently, those elements would not be included in the results

Aydin
  • 15,016
  • 4
  • 32
  • 42