1

我认为这应该很简单。

我有这个字符串:

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

应该用类似的东西代替

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

我很确定这不会很顺利。到目前为止,我有这个:

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

谁能指出我正确的方向?

任何帮助表示赞赏!

4

3 回答 3

2

试试这个:

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));
于 2009-10-16T18:07:25.380 回答
1

你为什么不说你也想处理嵌套标签......

我几乎没有使用过正则表达式,但事情是这样的:

    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;
    }
于 2009-10-16T23:36:42.937 回答
0

这应该是您在 dot net 中的正则表达式:

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

        string name = regexQuote.Match().Groups["name"];
        string id = regexQuote.Match().Groups["id"];
        //..
于 2009-10-16T18:08:48.090 回答