简单的正则表达式 - 替换C#中论坛主题中的引用信息

时间:2009-10-16 17:54:38

标签: c# regex quotes

我认为这应该是非常简单的。

我有这个字符串:

[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\]");

有人能指出我正确的方向吗?

任何帮助表示赞赏!

3 个答案:

答案 0 :(得分: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));

答案 1 :(得分: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;
    }

答案 2 :(得分:0)

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

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

        string name = regexQuote.Match().Groups["name"];
        string id = regexQuote.Match().Groups["id"];
        //..