正则表达式使用C#将Markdown内联链接转换为HTML链接 [英] Regex convert a Markdown inline link into an HTML link with C#

查看:53
本文介绍了正则表达式使用C#将Markdown内联链接转换为HTML链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用C#写一个非常基本的Markdown到HTML转换器.

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

我设法编写了正则表达式来转换粗体和斜体文本,但是我正努力提出一个正则表达式,该正则表达式可以将markdown链接转换为html中的链接标记.

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.

例如:

This is a [link](/url) 

应该成为

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?

推荐答案

尝试替换此

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

与此:

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

示例: https://regex101.com/r/ur35s8/2

这篇关于正则表达式使用C#将Markdown内联链接转换为HTML链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆