how to extract first image url from markdown #164

Closed
opened 2026-01-29 14:29:16 +00:00 by claunia · 3 comments
Owner

Originally created by @joeaudette on GitHub (Nov 20, 2017).

Sorry if this is a stupid question. I am trying to extract the first image url found in a markdown string and have been struggling to do it with regex. I wonder is there an easy way to do it with Markdig?

Originally created by @joeaudette on GitHub (Nov 20, 2017). Sorry if this is a stupid question. I am trying to extract the first image url found in a markdown string and have been struggling to do it with regex. I wonder is there an easy way to do it with Markdig?
claunia added the question label 2026-01-29 14:29:16 +00:00
Author
Owner

@xoofx commented on GitHub (Nov 20, 2017):

Yeah, sorry for the lack of documentation, hopefully it will come next year. In the meantime, you can achieve what you are looking for by walking the document AST:

var doc = Markdown.Parse("There is a ![link](/yoyo)");
// Select paragraph blocks and then all LinkInline and take the first one
var link = doc.Descendants<ParagraphBlock>().SelectMany(x => x.Inline.Descendants<LinkInline>()).FirstOrDefault(l => l.IsImage);
Console.WriteLine(link.Url);
@xoofx commented on GitHub (Nov 20, 2017): Yeah, sorry for the lack of documentation, hopefully it will come next year. In the meantime, you can achieve what you are looking for by walking the document AST: ```c# var doc = Markdown.Parse("There is a ![link](/yoyo)"); // Select paragraph blocks and then all LinkInline and take the first one var link = doc.Descendants<ParagraphBlock>().SelectMany(x => x.Inline.Descendants<LinkInline>()).FirstOrDefault(l => l.IsImage); Console.WriteLine(link.Url); ```
Author
Owner

@joeaudette commented on GitHub (Nov 20, 2017):

@xoofx thanks for the speedy response! That looks like it would get the first link, but how can I make sure I am getting the first image url not just the first link? I guess I can just check the file extension of the url but was hoping there might be a specific way to get images. I can work with that though so thanks!

@joeaudette commented on GitHub (Nov 20, 2017): @xoofx thanks for the speedy response! That looks like it would get the first link, but how can I make sure I am getting the first image url not just the first link? I guess I can just check the file extension of the url but was hoping there might be a specific way to get images. I can work with that though so thanks!
Author
Owner

@joeaudette commented on GitHub (Nov 20, 2017):

doh!, it does show how to get images, just needed to scroll your answer. Thanks again!

@joeaudette commented on GitHub (Nov 20, 2017): doh!, it does show how to get images, just needed to scroll your answer. Thanks again!
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: starred/markdig#164