0

我想转:

[quote]Hello![/quote]

进入:

<div class="quoted-text">Hello!</div>

这段代码是我最接近工作的代码:

var r = new Regex(@"\[quote\]([^\]]+)\[\/quote\]", RegexOptions.Multiline | RegexOptions.IgnoreCase);
rawComment = r.Replace(rawComment, "<div class=\"quoted-text\">$1</div>");

但是,对于嵌套引号,它不会正确出现。它似乎只转换最里面的报价。一个测试用例是:

[quote]
    test
    [quote]
        nest
        [quote]
            nest
        [/quote]
    [/quote]
[/quote]

结果如下:

[quote]
    test
    [quote]
        nest
        <div class="quoted-text">
            nest
        </div>
    [/quote]
[/quote]

谁能告诉我如何按预期进行这项工作?

4

1 回答 1

1

我看不出您需要将引号解析为块的原因。因此,最简单的解决方案是将每个令牌替换为您想要的令牌。以下是 LinqPad 的示例:

void Main()
{

    var rawComment =
"[quote]\n" +
"   test\n" +
"   [quote]\n" +
"       nest\n" +
"       [quote]\n" +
"           nest\n" +
"       [/quote]\n" +
"   [/quote]\n" +
"[/quote]\n";

    var start = new Regex(@"\[quote\]", RegexOptions.IgnoreCase);
    var end = new Regex(@"\[\/quote\]", RegexOptions.IgnoreCase);
    rawComment = start.Replace(rawComment, "<div class=\"quoted-text\">");
    rawComment = end.Replace(rawComment, "</div>");

    rawComment.Dump();
}

这会产生以下结果:

<div class="quoted-text">
  test
  <div class="quoted-text">
    nest
    <div class="quoted-text">
      nest
    </div>
  </div>
</div>
于 2012-09-13T15:07:33.120 回答