用于将mark转换为HTML的正则表达式

mat*_*uma 7 html c# regex markdown

如何编写正则表达式将mark转换为HTML?例如,您可以输入以下内容:

This would be *italicized* text and this would be **bold** text
Run Code Online (Sandbox Code Playgroud)

然后需要将其转换为:

This would be <em>italicized</em> text and this would be <strong>bold</strong> text
Run Code Online (Sandbox Code Playgroud)

与stackoverflow使用的标记向下编辑控件非常相似.

澄清

对于它的价值,我正在使用C#.此外,这些是我想要允许的唯一真正的标签/降价.转换的文本量将少于300个字符左右.

Tim*_*ker 6

最好的方法是找到一个版本的Markdown库移植到你正在使用的任何语言(你没有在你的问题中指定).


既然您已经明确表示只需要处理STRONG和EM,并且您正在使用C#,我建议您查看Markdown.NET以了解这些标记是如何实现的.如您所见,它实际上是两个表达式.这是代码:

private string DoItalicsAndBold (string text)
{
    // <strong> must go first:
    text = Regex.Replace (text, @"(\*\*|__) (?=\S) (.+?[*_]*) (?<=\S) \1", 
                          new MatchEvaluator (BoldEvaluator),
                          RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline);

    // Then <em>:
    text = Regex.Replace (text, @"(\*|_) (?=\S) (.+?) (?<=\S) \1",
                          new MatchEvaluator (ItalicsEvaluator),
                          RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline);
    return text;
}

private string ItalicsEvaluator (Match match)
{
    return string.Format ("<em>{0}</em>", match.Groups[2].Value);
}

private string BoldEvaluator (Match match)
{
    return string.Format ("<strong>{0}</strong>", match.Groups[2].Value);
}
Run Code Online (Sandbox Code Playgroud)


jop*_*jop 5

一个正则表达式不会.每个文本标记都有自己的html翻译器.更好地了解现有转换器的实现方式,以了解其工作原理.

http://en.wikipedia.org/wiki/Markdown#See_also