正则表达式格式化嵌套BB [quote]标签

时间:2012-09-13 14:54:26

标签: c# regex replace

我想转:

[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]

有人能告诉我如何按预期完成这项工作吗?

1 个答案:

答案 0 :(得分: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>