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

橙三吉。 提交于 2020-08-19 07:22:21

问题


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?


回答1:


Try replacing this

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

With this:

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

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




回答2:


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



来源:https://stackoverflow.com/questions/40177342/regex-convert-a-markdown-inline-link-into-an-html-link-with-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!