Ruby gsub 函数
我正在尝试为我的 Rails 论坛创建 BBcode [code] 标签,但我对表达式有疑问:
param_string.gsub!( /\[code\](.*?)\[\/code\]/im, '<pre>\1</pre>' )
How do I get what the regex match returns (the text in Between the [code][/code] tag),并转义所有 html 和其中的一些其他字符?
我已经尝试过这个:
param_string.gsub!( /\[code\](.*?)\[\/code\]/im, '<pre>' + my_escape_function('\1') + '</pre>' )
但没有成功。它只是将“\1”作为字符串传递给函数。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该注意正则表达式的贪婪行为。所以正确的代码如下所示:
escape_method
则如下所示:You should take care of the greedy behavior of the regular expressions. So the correct code looks like this:
The
escape_method
then looks like this:这里有人发布了答案,但他们已经删除了。
我已经尝试过他们的建议,并通过一些小改动使其发挥作用。不管你是谁,谢谢! :)
这里是
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
您只需使用
"
"
作为替换值即可。You can simply use
"<pre>#{$1}</pre>"
for your replacement value.