[英]Removing a pattern from the beginning and end of a string in ruby
所以我發現自己需要在我正在處理的項目中從字符串的開頭和結尾刪除<br />
標簽。 我做了一個快速的小方法來完成我需要做的事情,但我不相信這是做這類事情的最好方法。 我懷疑可能有一個方便的正則表達式,我可以用它來做幾行。 這是我得到的:
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可以采用正則表達式:
text.gsub!(/(<br \/>\s*)*$/, '')
text.gsub!(/^(\s*<br \/>)*/, '')
text.strip!
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'
你可以使用chomp!
和slice!
方法。 請參閱: http : //ruby-doc.org/core-1.8.7/String.html
def remove_breaks(text)
text.gsub((%r{^\s*<br />|<br />\s*$}, '')
end
%r{...}
是另一種指定正則表達式的方法。 %r的優點是你可以選擇自己的分隔符。 使用{}作為分隔符意味着不必逃避/。
請改用替換方法
str.replace("<br/>", "")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.