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,143
  • 13
  • 42
  • 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,630
  • 4
  • 34
  • 53
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,442
  • 9
  • 49
  • 80
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
  • 10,668
  • 5
  • 27
  • 47
1

You can just use simple regex:

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

http://regex101.com/r/cD0cT0

melvas
  • 2,306
  • 24
  • 29