Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex convert a Markdown inline link into an HTML link with C#

Tags:

c#

regex

markdown

I'm writing a very basic Markdown to HTML converter in C#.

I managed to write regular expressions to convert bold and italic text, but I'm struggling to come up with a piece of regex which can transform a markdown link into a link tag in html.

For example:

This is a [link](/url) 

should become

This is a <a href='/url'>link</a>

This is my code so far:

var bold = new Regex(@"(\*\*|__) (?=\S) (.+?[*_]*) (?<=\S) \1", // Regex for bold text
        RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline | RegexOptions.Compiled);
var italic = new Regex(@"(\*|_) (?=\S) (.+?) (?<=\S) \1", // Regex for italic text
        RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline | RegexOptions.Compiled);
var anchor = new Regex(@"??????????", // Regex for hyperlink text
        RegexOptions.Singleline | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);

content = bold.Replace(content, @"<b>$2</b>");
content = italic.Replace(content, @"<i>$2</i>");
content = anchor.Replace(content, @"<a href='$3'>$2</a>");

What kind of regular expression can accomplish this?

like image 711
tocqueville Avatar asked Oct 21 '16 13:10

tocqueville


2 Answers

in markdown there may be two ways of url:

[sample link](http://example.com/)
[sample link](http://example.com/ "with title")

regex from the solution that Addison showed would work only at first type, and only on urls starting with /. for example a [link name](http://stackoverflow.com/questions/40177342/regex-convert-a-markdown-inline-link-into-an-html-link-with-c-sharp "link to this question") wont work

here is regex working at both

\[([^]]*)\]\(([^\s^\)]*)[\s\)]

https://regex101.com/r/kZbw7g/1

like image 142
Misiakw Avatar answered Nov 08 '22 23:11

Misiakw


Try replacing this

\[(.+)\]\((\/.+)\)

With this:

<a href='\2'>\1</a>

Example: https://regex101.com/r/ur35s8/2

like image 5
Addison Avatar answered Nov 08 '22 22:11

Addison