c# – 将标记向下转换为HTML的正则表达式

前端之家收集整理的这篇文章主要介绍了c# – 将标记向下转换为HTML的正则表达式前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何编写正则表达式将mark转换为 HTML?例如,您可以输入以下内容
This would be *italicized* text and this would be **bold** text

然后需要将其转换为:

This would be <em>italicized</em> text and this would be <strong>bold</strong> text

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

澄清

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

解决方法

最好的方法是找到一个版本的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);
}
原文链接:https://www.f2er.com/csharp/98945.html

猜你在找的C#相关文章