在Python中,我可以从像
这样的字符串中删除空格,新行或随机字符>>> '/asdf/asdf'.strip('/')
'asdf/asdf' # Removes / from start
>>> '/asdf/asdf'.strip('/f')
'asdf/asd' # Removes / from start and f from end
>>> ' /asdf/asdf '.strip()
'/asdf/asdf' # Removes white space from start and end
>>> '/asdf/asdf'.strip('/as')
'df/asdf' # Removes /as from start
>>> '/asdf/asdf'.strip('/af')
'sdf/asd' # Removes /a from start and f from end
但Ruby的String#strip方法不接受任何参数。我总是可以回到使用正则表达式,但有没有方法/方法从Ruby中的字符串(后面和前面)中删除随机字符而不使用正则表达式?
答案 0 :(得分:6)
您可以使用正则表达式:
"atestabctestcb".gsub(/(^[abc]*)|([abc]*$)/, '')
# => "testabctest"
当然,您也可以将此作为一种方法:
def strip_arbitrary(s, chars)
r = chars.chars.map { |c| Regexp.quote(c) }.join
s.gsub(/(^[#{r}]*)|([#{r}]*$)/, '')
end
strip_arbitrary("foobar", "fra") # => "oob"
答案 1 :(得分:3)
Python的条带有点不寻常。它从任一端删除任何与参数中任何一个匹配的字符。
我认为你需要2 .subs
。一个从头开始剥离,一个从末尾剥离
irb(main):001:0> 'asdf/asdf'.sub(/^[\/]*/, '').sub(/[\/]*$/, '')
=> "asdf/asdf"
irb(main):002:0> 'asdf/asdf'.sub(/^[\/f]*/, '').sub(/[\/f]*$/, '')
=> "asdf/asd"
irb(main):003:0> ' asdf/asdf'.sub(/^[ ]*/, '').sub(/[ ]*$/, '')
=> "asdf/asdf"