在 Python 中,我们可以使用.strip()
字符串的方法来删除所选字符的前导或尾随出现:
>>> print " (Removes (only) leading & trailing brackets & ws ) ".strip(" ()")
'Removes (only) leading & trailing brackets & ws'
我们如何在 Ruby 中做到这一点?Ruby 的strip
方法不接受任何参数,只去除空格。
ruby 中没有这样的方法,但你可以很容易地定义它:
def my_strip(string, chars)
chars = Regexp.escape(chars)
string.gsub(/\A[#{chars}]+|[#{chars}]+\z/, "")
end
my_strip " [la[]la] ", " []"
#=> "la[]la"
"[[ ] foo [] boo ][ ]".gsub(/\A[ \[\]]+|[ \[\]]+\Z/,'')
=> "foo [] boo"
也可以缩短为
"[[ ] foo [] boo ][ ]".gsub(/\A[][ ]+|[][ ]+\Z/,'')
=> "foo [] boo"
ruby 中没有这样的方法,但你可以很容易地定义它:
class String
alias strip_ws strip
def strip chr=nil
return self.strip_ws if chr.nil?
self.gsub /^[#{Regexp.escape(chr)}]*|[#{Regexp.escape(chr)}]*$/, ''
end
end
这将满足所要求的要求:
> "[ [] foo [] boo [][]] ".strip(" []")
=> "foo [] boo"
在不那么极端的情况下仍然做你期望的事情。
> ' _bar_ '.strip.strip('_')
=> "bar"
开心!
试试gsub方法:
irb(main):001:0> "[foo ]".gsub(/\As+[/,'')
=> "foo ]"
irb(main):001:0> "foo ]".gsub(/s+]\Z/,'')
=> "foo"
等等
您可以使用: str.chomp('.') 适用于尾随字符,您可以反转字符串作为前导字符: str.reverse.chomp('.').reverse
要同时执行这两项操作,您可以: str.chomp('.').reverse.chomp('.').reverse
注意: chomp 默认只删除一次出现
Ruby 现在包括对剥离的完全支持
lstrip:只去除字符串的前导部分 rstrip:只去除字符串的结尾部分 strip:去除字符串的开头和结尾
试试String#delete
方法:(1.9.3可用,其他版本不清楚)
前任:
1.9.3-p484 :003 > "hehhhy".delete("h")
=> "ey"