Search code examples
c#asp.netregextagsforum

I need help modifying a C# regular expression


I am using a regex to detect forum tags within posts, such as "[quote]text[/quote]" and then replace them with HTML formatting. I posted a question Forum tags. What is the best way to implement them? about a problem with nested tags.

I have an idea, but I need someone's help to help me expand on it (because I suck at regex).

I need this regex modified

string regex = @"\[([^=]+)[=\x22']*(\S*?)['\x22]*\](.+?)\[/(\1)\]";

Right now this matches an opening and closing tag, with match groups for the tag name, the tag content, and an optional value like the value after the equals in this forum tag [url=www.google.com]click me[/url].

What I need is for the expression to match the opening tag OR the closing tag and have a match group containing the tag name (including the '/' for the closing tag). I then want to iterate through them sort of like this:

Dictionary<string, int> tagCollection = new Dictionary<string, int>();
inputString = Regex.Replace(inputString, @"expression I'm asking for here",
match =>
{
    string tag = match.Groups[0].Value;
    bool isOpeningTag = tag.StartsWith("/");
    tag = isOpeningTag ? tag : tag.Replace("/","");
    int tagCount = 0;
    if (tagCollection.ContainsKey(tag) && isOpeningTag)
    {
        tagCount = tagCollection[tag];
        tagCollection[tag] = tagCount + 1;
    }
    else if (tagCollection.ContainsKey(tag) && !isOpeningTag)
    {
        tagCount = tagCollection[tag];
        tagCollection[tag] = tagCount - 1;
    }
    else if (!tagCollection.ContainsKey(tag) && isOpeningTag)
        tagCollection.Add(tag, tagCount);

    string newTag = match.Value.Replace(tag, tag + tagCount.ToString());
    return newTag;
});

So now, each tag is appended with a number and I could use the original regex to perform the tag functions and properly handle nested tags as separate tags. So really, all I need from you guys is the regex I listed to be modified in the manner I specified.

Feel free to offer other suggestions as well but I would ask that actual answers focus on the regex modification and not whether or not this is the best way to go about the problem.

Thanks!


Solution

  • \[([^=]+)[=\x22']*(\S*?)['\x22]*\]|\[/(\1)\]