Search code examples
c#regexmultilinephpbbbbcode

Parse multiline BBCode with C# Regex


I'm working on a C# class to parse BBCodes out of text pulled from a database for PHPBB posts. On the PHPBB there is a custom BBCode added which looks like this:

[deck={TEXT1}]{TEXT2}[/deck]

Which, sitting in the database, looks like this:

[deck=FirstText:13giljne]Large Multiline Text[/deck:13giljne]

I'm attempting to replace that using a Regex in C#. My C# looks like this:

string text = "[deck=FirstText:13giljne]Large Multiline Text[/deck:13giljne]";
string replace = "my replacement string";
string pattern = @"\[deck=((.|\n)*?)(?:\s*)\]((.|\n)*?)\[/deck(?:\s*)\]";
RegexOptions options = RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline;
Regex regex = new Regex(pattern, options);
string result = regex.Replace(text, replace);

I'm pretty sure it all just comes down to my Regex pattern being wrong. Which comes as no surprise to me, since Regex isn't exactly my strong suit.

Thanks in advance. Any help is greatly appreciated.

EDIT: Since some people found it unclear, I'll add larger examples.

Source text:

[deck=Foo:13giljne]
    Item #1
    Item #2
    Item #3
    Item #4
[/deck:13giljne]

Desired result:

<span>Foo</span>
<div>
    Item #1
    Item #2
    Item #3
    Item #4
</div>

Hopefully this gives a clearer picture of what I'm trying to do.


Solution

  • I think your regex shows that you need to match "First Text" and "Large Multiline Text".

    \[deck=([^\:]+?):(?:[^\]]+)\]([^\[]+?)\[/deck:(?:[^\]]+)\]
    

    This should help and it's very close to yours.