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

本文关键字:正则表达式 嵌套 bbcode 来自 | 更新日期: 2023-09-27 17:56:15

我已经到处寻找一个可以在 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>

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

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

没有必要

递归地执行此操作或匹配报价的相应开头和结尾 - 最后,必须替换相同数量的开始和结束。这可以为任何嵌套完成

,例如:
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>$1</legend>$2</fieldset>");
    Console.WriteLine(s);
}

你可以试试这个:

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>$1</legend>$2<fieldset class='"bbquote'"><legend>$3</legend>$4</fieldset>$5</fieldset>"));
        }
    }
}

它捕获 5 组:

  • $1 鲍勃
  • $2 我不敢相信你这么说:
  • $3 乔
  • $4 我喜欢灯。
  • $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>