伙计们,我有这个 wiki 格式化算法,我在Stacked使用它来从“wiki 语法”创建 HTML,我不确定我当前使用的是否足够好、最优或包含错误,因为我是不是真正的“正则表达式大师”。这是我目前正在使用的;
// Body is wiki content...
string tmp = Body.Replace("&", "&").Replace("<", "<").Replace(">", ">");
// 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>^>.+$)",
"<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)
如果有一些“正则表达式大师”想回顾这个正则表达式逻辑,我会非常感激 :)