[英]Removing a pattern from the beginning and end of a string in ruby
So I found myself needing to remove <br />
tags from the beginning and end of strings in a project I'm working on. 所以我发现自己需要在我正在处理的项目中从字符串的开头和结尾删除
<br />
标签。 I made a quick little method that does what I need it to do but I'm not convinced it's the best way to go about doing this sort of thing. 我做了一个快速的小方法来完成我需要做的事情,但我不相信这是做这类事情的最好方法。 I suspect there's probably a handy regular expression I can use to do it in only a couple of lines.
我怀疑可能有一个方便的正则表达式,我可以用它来做几行。 Here's what I got:
这是我得到的:
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
Now the "<br />"
could really be anything, and it'd probably be more useful to make a general use function that takes as an argument the string that needs to be stripped from the beginning and end. 现在
"<br />"
实际上可以是任何东西,并且制作一个通用的函数可能更有用,该函数将需要从开头和结尾剥离的字符串作为参数。
I'm open to any suggestions on how to make this cleaner because this just seems like it can be improved. 我对如何使这个更清洁的任何建议持开放态度,因为这似乎可以改进。
gsub can take a regular expression: 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'
You can use chomp!
你可以使用
chomp!
and slice!
和
slice!
methods. 方法。 See: http://ruby-doc.org/core-1.8.7/String.html
请参阅: http : //ruby-doc.org/core-1.8.7/String.html
def remove_breaks(text)
text.gsub((%r{^\s*<br />|<br />\s*$}, '')
end
%r{...}
is another way to specify a regular expression. %r{...}
是另一种指定正则表达式的方法。 The advantage of %r is that you can pick your own delimeter. %r的优点是你可以选择自己的分隔符。 Using {} for the delimiters means not having to escape the /'s.
使用{}作为分隔符意味着不必逃避/。
请改用替换方法
str.replace("<br/>", "")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.