2

伙计们,我有这个 wiki 格式化算法,我在Stacked使用它来从“wiki 语法”创建 HTML,我不确定我当前使用的是否足够好、最优或包含错误,因为我是不是真正的“正则表达式大师”。这是我目前正在使用的;

// Body is wiki content...
string tmp = Body.Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;");
// Sanitizing carriage returns...
tmp = tmp.Replace("\\r\\n", "\\n");

// Replacing dummy links...
tmp = Regex.Replace(
" " + tmp,
"(?<spaceChar>\\s+)(?<linkType>http://|https://)(?<link>\\S+)",
"${spaceChar}<a href=\"${linkType}${link}\"" + nofollow + ">${link}</a>",
RegexOptions.Compiled).Trim();

// Replacing wiki links
tmp = Regex.Replace(tmp,
"(?<begin>\\[{1})(?<linkType>http://|https://)(?<link>\\S+)\\s+(?<content>[^\\]]+)(?<end>[\\]]{1})",
"<a href=\"${linkType}${link}\"" + nofollow + ">${content}</a>",
RegexOptions.Compiled);

// Replacing bolds
tmp = Regex.Replace(tmp,
"(?<begin>\\*{1})(?<content>.+?)(?<end>\\*{1})",
"<strong>${content}</strong>",
RegexOptions.Compiled);

// Replacing italics
tmp = Regex.Replace(tmp,
"(?<begin>_{1})(?<content>.+?)(?<end>_{1})",
"<em>${content}</em>",
RegexOptions.Compiled);

// Replacing lists
tmp = Regex.Replace(tmp,
"(?<begin>\\*{1}[ ]{1})(?<content>.+)(?<end>[^*])",
"<li>${content}</li>",
RegexOptions.Compiled);
tmp = Regex.Replace(tmp,
"(?<content>\\<li\\>{1}.+\\<\\/li\\>)",
"<ul>${content}</ul>",
RegexOptions.Compiled);

// Quoting
tmp = Regex.Replace(tmp,
"(?<content>^&gt;.+$)",
"<blockquote>${content}</blockquote>",
RegexOptions.Compiled | RegexOptions.Multiline).Replace("</blockquote>\n<blockquote>", "\n");

// Paragraphs
tmp = Regex.Replace(tmp,
"(?<content>)\\n{2}",
"${content}</p><p>",
RegexOptions.Compiled);

// Breaks
tmp = Regex.Replace(tmp,
"(?<content>)\\n{1}",
"${content}<br />",
RegexOptions.Compiled);

// Code
tmp = Regex.Replace(tmp,
"(?<begin>\\[code\\])(?<content>[^$]+)(?<end>\\[/code\\])",
"<pre class=\"code\">${content}</pre>",
RegexOptions.Compiled);

// Now hopefully tmp will contain perfect HTML

觉得这里的代码很难看的朋友,也可以看这里...

这是完整的“wiki 语法”;

这里的语法:

Link; [http://x.com text]

*bold* (asterisk on both sides)

_italic_ (underscores on both sides)

* Listitem 1
* Listitem 2
* Listitem 3
(the above is asterixes but so.com also creates lists from it)

2 x Carriage Return is opening a new paragraph

1 x Carriage Return is break (br)

[code]
if( YouDoThis )
  YouCanWriteCode();
[/code]


> quote (less then operator)

如果有一些“正则表达式大师”想回顾这个正则表达式逻辑,我会非常感激 :)

4

1 回答 1

4

不要在这个任务中使用正则表达式,这很危险,不会让你开心。用户输入可能会以超出想象的方式被破坏(故意或意外),没有正则表达式能够涵盖所有可能的情况。

具有上下文和嵌套概念的解析器在这里要好得多。

您能否发布您允许的语法的完整示例,以便人们可以开始告诉您如何解析它?


编辑:您可以研究为此使用(可能修改的)Markdown解析器的可能性。有一个可用的 .NET 开源变体:Markdown.NET,至少查看源代码可能是值得的。也许修改它以满足您的需求并不太难。

于 2008-12-04T08:32:24.510 回答