tags:

views:

362

answers:

3

Hi!

This should be pretty straightforward I would think.

I have this string:

[quote=Joe Johnson|1]Hi![/quote]

Which should be replaced with something like

<div class="quote">Hi!<div><a href="users/details/1">JoeJohnson</a></div></div>

I'm pretty shure this is not going very well. So far I have this:

Regex regexQuote = new Regex(@"\[quote\=(.*?)\|(.*?)\](.*?)\[\/quote\]");

Can anyone point me in the right direction?

Any help appreciated!

+1  A: 

Try this:

string pattern = @"\[quote=(.*?)\|(\d+)\]([\s\S]*?)\[/quote\]";
string replacement = 
  @"<div class=""quote"">$3<div><a href=""users/details/$2"">$1</a></div></div>";

Console.WriteLine(
    Regex.Replace(input, pattern, replacement));
Rubens Farias
you forgot the @ in the replacement string
Itay
@Itay, fixed ty
Rubens Farias
Works perfectly! Accepted this, for me it was the most obvious solution. Theres just one problem. How to deal with [quote=Bla|1] Outer quote [quote=Jon|2] Inner quote [/quote][/quote]
Kordonme
you should have said so
Itay
A: 

this should be your regex in dot net:

\[quote\=(?<name>(.*))\|(?<id>(.*))\](?<content>(.*))\[\/quote\]

        string name = regexQuote.Match().Groups["name"];
        string id = regexQuote.Match().Groups["id"];
        //..
Itay
An awful lot of greedy `.*`-s you got there. Better be more specific, if you ask me.
Bart Kiers
thought about it, but i've just copied the original.. maybe he does want to find anything similar to inform the user it's illegal..
Itay
+1  A: 

why didn't you said you want to deal with nested tags as well...

i've barely ever worked with regex, but here the thing:

    static string ReplaceQuoteTags(string input)
    {
        const string closeTag = @"[/quote]";
        const string pattern = @"\[quote=(.*?)\|(\d+?)\](.*?)\[/quote\]"; //or whatever you prefer
        const string replacement = @"<div class=""quote"">{0}<div><a href=""users/details/{1}"">{2}</a></div></div>";

        int searchStartIndex = 0;
        int closeTagIndex = input.IndexOf(closeTag, StringComparison.OrdinalIgnoreCase);

        while (closeTagIndex > -1)
        {
            Regex r = new Regex(pattern, RegexOptions.RightToLeft | RegexOptions.IgnoreCase);

            bool found = false;
            input = r.Replace(input,
                x =>
                {
                    found = true;
                    return string.Format(replacement, x.Groups[3], x.Groups[2], x.Groups[1]);
                }
                , 1, closeTagIndex + closeTag.Length);

            if (!found)
            {
                searchStartIndex = closeTagIndex + closeTag.Length;
                //in case there is a close tag without a proper corresond open tag.
            }

            closeTagIndex = input.IndexOf(closeTag, searchStartIndex, StringComparison.OrdinalIgnoreCase);
        }

        return input;
    }
Itay