Ruby gsub function

你离开我真会死。 提交于 2019-12-04 19:42:29

You should take care of the greedy behavior of the regular expressions. So the correct code looks like this:

html.gsub!(/\[(\S*?)\](.*?)\[\/\1\]/) { |m| escape_method($1, $2) }

The escape_method then looks like this:

def escape_method( type, string )
  case type.downcase
    when 'code'
      "<pre>#{string}</pre>"
    when 'bold'
      "<b>#{string}</b>"
    else
       string
  end
end

Someone here posted an answer, but they've deleted it.

I've tried their suggestion, and made it work with a small change. Whoever you are, thanks! :)

Here it is

param_string.gsub!( /\[code\](.*?)\[\/code\]/im ) {|s| '<pre>' + my_escape_function(s) + '</pre>' }

You can simply use "<pre>#{$1}</pre>" for your replacement value.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!