所以我發現自己需要從正在處理的項目中字符串的開頭和結尾刪除<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 />"
真的可以是任何東西,它可能會是使一個通用函數,它作爲一個參數,需要從一開始剝離字符串更加有用,結束。
我接受任何關於如何使這種清潔劑的建議,因爲這似乎可以改進。
如果你正在尋找只是字符串操作使用正則表達式和gsub,但更具體地說,如果你正在尋找與其他html標籤這樣做,我會推薦一個解析器。 http://nokogiri.org/對於紅寶石來說,Nokogiri可能是最棒的。 – mpd 2010-04-30 10:14:55