Ruby gsub函数 [英] Ruby gsub function

查看:58
本文介绍了Ruby gsub函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我的rails论坛创建BBcode [code]标签,但表达式存在问题:

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

如何获取正则表达式匹配返回的内容([code] [/code]标记之间的文本),并转义其中的所有html和其他字符?

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?

我已经尝试过了:

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

但是没有用.它只是将"\ 1"作为字符串传递给函数.

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

推荐答案

您应注意正则表达式的贪婪行为.因此正确的代码如下所示:

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

然后escape_method看起来像这样:

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

这篇关于Ruby gsub函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆