【问题标题】:What is the perfect Regex for doing wiki formatting (.Net)?进行 wiki 格式化 (.Net) 的完美正则表达式是什么?
【发布时间】:2008-12-04 08:19:12
【问题描述】:

伙计们,我有这个 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

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

这里是完整的“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)

如果有一些“正则表达式大师”想要审查这个正则表达式逻辑,我将不胜感激:)

【问题讨论】:

  • 您是否找到了替代方案,或者您暂时仍使用正则表达式?

标签: .net regex wiki


【解决方案1】:

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

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

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


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

【讨论】:

    猜你喜欢
    • 2023-03-19
    • 2011-06-15
    • 1970-01-01
    • 1970-01-01
    • 2015-06-09
    相关资源
    最近更新 更多