来自 bbcode 的嵌套引号的正则表达式

Regex for Nested Quotes from bbcode

我到处寻找可以在 C# 中为此工作的正则表达式,但什么也找不到。我为 PHP 找到了很多,但不确定如何将其转换为 C#。所以我想做的是简单地创建一个正则表达式,递归地匹配引号的 bbcode,然后将其更改为 HTML。这是一个例子:

[quote="bob"]I can't believe that you said this: [quote="joe"]I love lamp.
[/quote] That's hilarious![/quote]

那应该变成:

<fieldset class="bbquote"><legend>bob</legend>I can't believe that you said 
this: <fieldset class="bbquote"><legend>joe</legend>I love lamp.</fieldset> 
That's hilarious!</fieldset>

我尝试过的所有正则表达式都惨遭失败。

你可以试试这个:

using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        String sample = "[quote=\"bob\"]I can't believe that you said this: [quote=\"joe\"]I love lamp.[/quote] That's hilarious![/quote]";
        Regex regex = new Regex(@"(?:(?:\[quote="")(\w+)(?:""\])?([^\[]+))(?:(?:\[quote="")(\w+)(?:""\])?([^\[]+))(?:[^\]]+\]\s)([^\[]+)(?:\[\/quote\])");

        Match match = regex.Match(sample);

        if (match.Success)
        {
            Console.WriteLine(regex.Replace(sample,"<fieldset class=\"bbquote\"><legend></legend><fieldset class=\"bbquote\"><legend></legend></fieldset></fieldset>"));
        }
    }
}

它捕获了 5 个组:

  • $1 鲍勃
  • $2 我不敢相信你这么说:
  • 3 美元
  • 4 美元我爱 lamp。
  • $5 太搞笑了!

您可以将其替换为:

<fieldset class="bbquote"><legend>bob</legend>I can't believe that you said this: <fieldset class="bbquote"><legend>joe</legend>I love lamp.</fieldset>That's hilarious!</fieldset>

不必递归地执行此操作或匹配引号的相应开头和结尾 - 最后,必须替换相同数量的开头和结尾。对于任何带有 e 的嵌套都可以实现这一点。例如:

void Main()
{
    String s = "[quote=\"bob\"]I can't believe that you said this: [quote=\"joe\"]I love lamp.[/quote] That's hilarious![/quote]";
    Regex r = new Regex(@"\[quote=""(\w+)""\](.*?)\[/quote]");
    while (r.Match(s).Success)
        s = r.Replace(s, "<fieldset class=\"bbquote\"><legend></legend></fieldset>");
    Console.WriteLine(s);
}