如何编写正则表达式将 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 使用的 mark down 编辑控件非常相似。
澄清
就其价值而言,我正在使用 C#。另外,这些是only我想要允许的真实标签/降价。转换的文本量将少于 300 个字符左右。
最好的方法是找到移植到您正在使用的任何语言的 Markdown 库版本(您没有在问题中指定)。
既然您已经澄清您只想处理 STRONG 和 EM,并且您正在使用 C#,我建议您看一下Markdown.NET http://www.aspnetresources.com/blog/markdown_announced.aspx看看这些标签是如何实现的。正如你所看到的,它实际上是两个表达式。这是代码:
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);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)