我在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\1?\]/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
答案 0 :(得分:0)
我的意思是
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