-3

i have this string

http://localhost:1209/Pages/ap-aria.aspx text: <p><img alt="" src="http://localhost:1209/ckeditor/plugins/imagebrowser/browser/Hydrangeas.jpg" style="width: 1024px; height: 768px;" />qswdqwdqweqweqe</p>

now i want get image tag.how i cant split this string that return just image tag to me ? i want get this result

<img alt="" src="http://localhost:1209/ckeditor/plugins/imagebrowser/browser/Hydrangeas.jpg" style="width: 1024px; height: 768px;" />

thank's for your help

user3243749
  • 43
  • 1
  • 7

3 Answers3

1

You shouldn't parse HTMl with regex (mandatory Regex-HTML link). Using an appropriate parser such as the HTML Agility Pack should do the trick. You can then combine this and this previous SO posts to do what you are after.

Community
  • 1
  • 1
npinti
  • 51,780
  • 5
  • 72
  • 96
0

You can use a regex to extract the image tag. You need a non-greedy match, that stops at the first occurrence of the end of the tag (/> or </img>). See this link for a demo.

To put this into practice:

        string text = "http://localhost:1209/Pages/ap-aria.aspx text: <p><img alt=\"\" src=\"http://localhost:1209/ckeditor/plugins/imagebrowser/browser/Hydrangeas.jpg\" style=\"width: 1024px; height: 768px;\" />qswdqwdqweqweqe</p>";
        Regex regex = new Regex("(<img.+?(/>|</img>))");

        if (regex.IsMatch(text))
        {
            //the text contains an img tag.
            string imgTag = regex.Match(text).Captures[0].Value;
        }
Bas
  • 26,772
  • 8
  • 53
  • 86
0

If you need to parse html use an available library like HtmlAgilityPack:

string result = null;
var htmlDoc = new HtmlAgilityPack.HtmlDocument();
htmlDoc.LoadHtml(htmlText);
var img = htmlDoc.DocumentNode.Descendants("img").FirstOrDefault();
if(img != null)
{
    result = img.OuterHtml;
}

Result:

<img alt="" src="http://localhost:1209/ckeditor/plugins/imagebrowser/browser/Hydrangeas.jpg" style="width: 1024px; height: 768px;">
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939