1
string str = "class=\"customer-service-rightside-content-widget\"> <div class=\"content_asset\"> <p><img width=\"1300\" height=\"426\" alt=\"\" src=\"~/media/C14BCC5F47D54252B371B67E718DAC02.ashx\" ";

How to retrieve src path alone from the below string. I have tried a couple of regex patters but i am not getting correct results.I am using C# regular expression.

Vignesh Kumar A
  • 27,863
  • 13
  • 63
  • 115
mark
  • 71
  • 3

3 Answers3

1

Try this Regex

<img([^>]*[^*]?)>

REGEX DEMO

Vignesh Kumar A
  • 27,863
  • 13
  • 63
  • 115
0

I suggest you to use HtmlAgilityPack to parse HTML (available from NuGet). But you should include opening and closing tags (assume you will have <div>) for this string, because currently you have some substring with tags being cut:

string str = "<div class=\"customer-service-rightside-content-widget\"> <div class=\"content_asset\"> <p><img width=\"1300\" height=\"426\" alt=\"\" src=\"~/media/C14BCC5F47D54252B371B67E718DAC02.ashx\"/></div>";
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(str);
var img = doc.DocumentNode.SelectSingleNode("//img[@src]");
var src = img.Attributes["src"].Value; 

Result:

~/media/C14BCC5F47D54252B371B67E718DAC02.ashx
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
0

This is a little messy, but its quick and simple and you wont have to install any packages like some of the other answers:

string str = "class=\"customer-service-rightside-content-widget\"> <div class=\"content_asset\"> <p><img width=\"1300\" height=\"426\" alt=\"\" src=\"~/media/C14BCC5F47D54252B371B67E718DAC02.ashx\" ";
            int srcIndex = str.IndexOf("~");
            str = str.Substring(srcIndex);
            var endIndex = str.IndexOf("\"");
            var thisIsYourSrc = str.Substring(0, endIndex); // this will be the value that's in your scr attribute

RESULT:

~/media/C14BCC5F47D54252B371B67E718DAC02.ashx

Jason Roell
  • 6,679
  • 4
  • 21
  • 28