Ruby gsub function

天大地大妈咪最大 提交于 2020-01-13 07:08:30

问题


I'm trying to create a BBcode [code] tag for my rails forum, and I have a problem with the expression:

param_string.gsub!( /\[code\](.*?)\[\/code\]/im, '<pre>\1</pre>' )

How do I get what the regex match returns (the text inbetween the [code][/code] tags), and escape all the html and some other characters in it?

I've tried this:

param_string.gsub!( /\[code\](.*?)\[\/code\]/im, '<pre>' + my_escape_function('\1') + '</pre>' )

but it didn't work. It just passes "\1" as a string to the function.


回答1:


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



回答2:


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>' }



回答3:


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



来源:https://stackoverflow.com/questions/1991945/ruby-gsub-function

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