从rails text </div>中删除<div>标记

时间:2014-11-06 18:59:35

标签: ruby-on-rails regex gsub

我尝试删除这样的div标签;

<div id="line_small_spacing" style="font-size: 15px; font-family: Arial, 'Open Sans'; height: 2px; width: 697px; color: #444444;">&nbsp;</div>

使用以下代码;

object.gsub(/<div.*?>|<\/div>/, '')

但它没有删除,gsub表达式有什么问题吗?

2 个答案:

答案 0 :(得分:3)

使用gsub!将所有修改应用于当前对象。

object.gsub!(/<div.*?>|<\/div>/, '')

gsub仅在您将其分配给变量

时才有效
a = object.gsub(/<div.*?>|<\/div>/, '')

参考: http://www.ruby-doc.org/core-2.1.4/String.html#method-i-gsub

答案 1 :(得分:0)

它对我有用,在创建对象时可能会丢失转义字符。

irb(main):003:0> object = '<div id="line_small_spacing" style="font-size: 15px; font-family: Arial, \'Open Sans\'; height: 2px; width: 697px; color: #444444;">&nbsp;</div>'
=> "<div id=\"line_small_spacing\" style=\"font-size: 15px; font-family: Arial, 'Open Sans'; height: 2px; width: 697px; color: #444444;\">&nbsp;</div>"
irb(main):007:0> a = object.gsub(/<div.*?>|<\/div>/, '')
=> "&nbsp;"
irb(main):008:0> a
=> "&nbsp;"