17

在 Python 中,我们可以使用.strip()字符串的方法来删除所选字符的前导或尾随出现:

>>> print " (Removes (only) leading & trailing brackets & ws ) ".strip(" ()")
'Removes (only) leading & trailing brackets & ws'

我们如何在 Ruby 中做到这一点?Ruby 的strip方法不接受任何参数,只去除空格。

4

7 回答 7

14

ruby 中没有这样的方法,但你可以很容易地定义它:

def my_strip(string, chars)
  chars = Regexp.escape(chars)
  string.gsub(/\A[#{chars}]+|[#{chars}]+\z/, "")
end

my_strip " [la[]la] ", " []"
#=> "la[]la"
于 2010-07-02T13:20:43.777 回答
3
"[[ ] foo [] boo ][ ]".gsub(/\A[ \[\]]+|[ \[\]]+\Z/,'') 
=> "foo [] boo"

也可以缩短为

"[[ ] foo [] boo ][ ]".gsub(/\A[][ ]+|[][ ]+\Z/,'') 
=> "foo [] boo"
于 2010-07-02T13:42:46.580 回答
2

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"

开心!

于 2013-07-08T05:43:34.880 回答
1

试试gsub方法:

irb(main):001:0> "[foo ]".gsub(/\As+[/,'')
=> "foo ]"

irb(main):001:0> "foo ]".gsub(/s+]\Z/,'')
=> "foo"

等等

于 2010-07-02T13:19:21.153 回答
1

您可以使用: str.chomp('.') 适用于尾随字符,您可以反转字符串作为前导字符: str.reverse.chomp('.').reverse

要同时执行这两项操作,您可以: str.chomp('.').reverse.chomp('.').reverse

注意: chomp 默认只删除一次出现

于 2021-07-31T13:15:00.977 回答
0

Ruby 现在包括对剥离的完全支持

lstrip:只去除字符串的前导部分 rstrip:只去除字符串的结尾部分 strip:去除字符串的开头和结尾

于 2022-01-13T21:25:00.767 回答
-1

试试String#delete方法:(1.9.3可用,其他版本不清楚)

前任:

    1.9.3-p484 :003 > "hehhhy".delete("h")
     => "ey"
于 2014-01-31T16:55:47.900 回答