【问题标题】:Simple regex - replace quote information in forum topic in C#简单的正则表达式 - 在 C# 中替换论坛主题中的报价信息
【发布时间】:2010-12-07 11:02:10
【问题描述】:

我认为这应该很简单。

我有这个字符串:

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

谁能指出我正确的方向?

任何帮助表示赞赏!

【问题讨论】:

    标签: c# regex quotes


    【解决方案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】:

      试试这个:

      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));
      

      【讨论】:

      • 你忘记了替换字符串中的@
      • 完美运行!接受了这一点,对我来说这是最明显的解决方案。只有一个问题。如何处理 [quote=Bla|1] 外引号 [quote=Jon|2] 内引号 [/quote] [/quote]
      【解决方案3】:

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

      \[quote\=(?&lt;name&gt;(.*))\|(?&lt;id&gt;(.*))\](?&lt;content&gt;(.*))\[\/quote\]

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

      【讨论】:

      • 一大堆贪婪的.*-s 你到了那里。如果你问我,最好更具体。
      • 想了想,但我只是复制了原版..也许他确实想找到类似的东西来告诉用户这是非法的..
      猜你喜欢
      • 2012-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多