2010-04-30 77 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的優點是你可以選擇你自己的分區。使用{}作爲分隔符意味着不必跳過/。

相關問題