2010-04-30 76 views
3

所以我发现自己需要从正在处理的项目中字符串的开头和结尾删除<br />标签。我做了一个快速的小方法,完成我所需要的工作,但我不相信这是做这类事情的最好方法。我怀疑可能有一个方便的正则表达式,我可以用它来做几行。下面是我的了:从ruby中字符串的开始和结尾中删除一个模式

def remove_breaks(text) 
    if text != nil and text != "" 
     text.strip! 

     index = text.rindex("<br />") 

     while index != nil and index == text.length - 6 
      text = text[0, text.length - 6] 

      text.strip! 

      index = text.rindex("<br />") 
     end 

     text.strip! 

     index = text.index("<br />") 

     while index != nil and index == 0 
      text = test[6, text.length] 

      text.strip! 

      index = text.index("<br />") 
     end 
    end 

    return text 
end 

现在"<br />"真的可以是任何东西,它可能会是使一个通用函数,它作为一个参数,需要从一开始剥离字符串更加有用,结束。

我接受任何关于如何使这种清洁剂的建议,因为这似乎可以改进。

+2

如果你正在寻找只是字符串操作使用正则表达式和gsub,但更具体地说,如果你正在寻找与其他html标签这样做,我会推荐一个解析器。 http://nokogiri.org/对于红宝石来说,Nokogiri可能是最棒的。 – mpd 2010-04-30 10:14:55

回答

7

GSUB可以采取一个正则表达式:

text.gsub!(/(<br \/>\s*)*$/, '') 
text.gsub!(/^(\s*<br \/>)*/, '') 
text.strip! 
+0

谢谢!这是最适合我现在需要的。 – seaneshbaugh 2010-04-30 11:29:03

-1

使用替换方法来代替

str.replace("<br/>", "") 
+0

不幸的是ruby的字符串替换不能以这种方式工作,根据http://ruby-doc.org/core/classes/String.html#M000786替换只是用整个参数替换整个字符串。显然这不是我想要的。即使它以这种方式工作,我只需要在字符串的开始和结尾处替换“
”,但不要触摸中间的任何字符。例如 remove_breaks(“


我想保持
所有这些东西在这里。
”) 应该返回 ‘我想保持
这东西都在这里。’ – seaneshbaugh 2010-04-30 09:43:08

3
class String 
    def strip_this!(t) 
     # Removes leading and trailing occurrences of t 
     # from the string, plus surrounding whitespace. 
     t = Regexp.escape(t) 
     sub!(/^(\s* #{t} \s*)+ /x, '') 
     sub!(/ (\s* #{t} \s*)+ $/x, '') 
    end 
end 

# For example. 
str = ' <br /> <br /><br /> foo bar <br /> <br /> ' 
str.strip_this!('<br />') 
p str      # => 'foo bar' 
+0

fgb的答案对我所要做的事情稍微好一些。对于我只在整个Rails应用程序的两个地方使用的东西,扩展字符串似乎有点多。然而,这绝对是一个非常好的通用解决方案,我可以告诉我将来会使用它。这是一个耻辱,我不能标记两个答案是正确的,因为这真的很酷。 – seaneshbaugh 2010-04-30 11:33:29

1
def remove_breaks(text) 
    text.gsub((%r{^\s*<br />|<br />\s*$}, '') 
end 

%r{...}是另一种方式来指定正则表达式。 %r的优点是你可以选择你自己的分区。使用{}作为分隔符意味着不必跳过/。

相关问题