tocqueville tocqueville - 1 year ago 112
C# Question

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

I'm writing a very basic Markdown to HTML converter in C#. I managed to write the Regex expressions to convert the bold and italic syntax, but I'm struggling with the link.

This is a [link](/url)
should become
This is a <a href='/url'>link</a>

This is my code:

// this works
var bold = new Regex(@"(\*\*|__) (?=\S) (.+?[*_]*) (?<=\S) \1", RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline | RegexOptions.Compiled);
// this works
var italic = new Regex(@"(\*|_) (?=\S) (.+?) (?<=\S) \1", RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline | RegexOptions.Compiled);
// what here?
var anchor = new Regex(@"??????????", 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 is the Regex expression I should use?

Answer Source

Try replacing this


With this:

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


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download