3

How can I take an < img tag from string? Sample string is given below. But too bad name and surname parts are dynamic and sometimes image names are numbers...

Lorem ipsum dolor sit amet <img src='http://www.mydomain.com/images/name_surname.jpg' /> Sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.

What I've tried so far:

sMyText.Substring(sDescription.IndexOf("<img"), count?!);

how to count the who image character length? This is where I fail. Please help..

Cute Bear
  • 3,223
  • 13
  • 44
  • 69

4 Answers4

4

Use regular expressions.

string sMyText = "Lorem ipsum dolor sit amet <img src='http://www.mydomain.com/images/name_surname.jpg' /> Sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.";

Match match = Regex.Match(sMyText, "<img[^>]+>");

if (match.Success)
    Console.WriteLine(match.Value);
TheQ
  • 6,858
  • 4
  • 35
  • 55
4

I really don't like parsing html with a regex (see this question). I'd suggest using something like HtmlAgilityPack. It may seem overkill for your example but you'll save yourself a lot of pain in the future!

var document = new HtmlDocument();
document.LoadHtml(html);
var links = document.DocumentNode.Descendants("img");
Community
  • 1
  • 1
Liath
  • 9,913
  • 9
  • 51
  • 81
2

A solution using LINQ:

string s = "Lorem ipsum dolor sit amet <img src='http://www.mydomain.com/images/name_surname.jpg' /> Sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.";

string img = new string(s.SkipWhile(c => c != '<').TakeWhile(c => c != '>').Concat(">".ToCharArray()).ToArray());

Console.WriteLine(img); // output: <img src='http://www.mydomain.com/images/name_surname.jpg' />
w.b
  • 11,026
  • 5
  • 30
  • 49
1

You can just use simple regex:

(?=\<)(.*?)(?<=\>)

http://regex101.com/r/cD0cT0

melvas
  • 2,346
  • 25
  • 29