删除 ruby 中嵌套的 [quote] 标签

Removing nested [quote] tags in ruby

我正在 Rails 中编写一个论坛应用程序,但我一直坚持限制嵌套引号。

我尝试使用正则表达式和递归,深入到每个匹配的标签,计算级别,如果当前级别大于最大值,则删除其中的所有内容。问题是我的正则表达式只匹配第一个 [quote] 和第一个看到的 [/quote],而不是预期的最后一个。

正则表达式只是对我正在使用的自定义 bbcode 库的文档中给出的内容的轻微调整(我对正则表达式知之甚少,过去我尽可能多地学习几天,但我仍然被困住了)。我对其进行了更改,使其包含 [quote]、[quote=name] 和 [quote=name;222]。有人可以检查我的代码并让我知道问题出在哪里吗?我会很感激。

def remove_nested_quotes(post_string, max_quotes, count)
    result = post_string.match(/\[quote(:.*)?(?:)?(.*?)(?:)?\](.*?)\[\/quote?\]/mi)

    if result.nil?
      return false
    elsif  (count = count+1) > max_quotes
      full_str = result[0]
      offset_beg = result.begin(3)
      offset_end = result.end(3)
      excess_quotes = full_str[offset_beg ..offset_end ]
      new_string = full_str.slice(excess_quotes )
      return new_string
    else
      offset_beg = result.begin(3)
      offset_end = result.end(3)
      full_str = result[0]
      inner_string = full_str[offset_beg..offset_end]
      return remove_nested_quotes(inner_string , max, count)
   end
end

我的意思是

counter = 0
max = 5

loop do
    matched = false
    string.match /endquote|quote/ do |match|
       matched = true
       if endquote matched
         counter -= 1     
       else # quote matched
         counter += 1
       end
       if counter > max
         # Do something, break or return             
       else
         string = match.post_match
       end
    end
    break unless matched
end