python - 如何在 Ruby 中实现类似 Python 的字符串剥离?

标签 python ruby string strip

在 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 中的字符串(前后)中去除随机字符?

最佳答案

您可以使用正则表达式:

"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"

关于python - 如何在 Ruby 中实现类似 Python 的字符串剥离?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12262621/

相关文章:

Python - 类方法多进程安全吗?

ruby - 通过 Apache mod_fcgid 服务的 Redmine 2.4.2 返回错误 500

ruby-on-rails - 仅使用默认语言环境的 Rails 模型

c# - 删除一个词及其后的所有内容

python - 即使我从目录外部执行文件,如何获取正在执行的文件的目录名?

python - 使用 Python 2.7 时间模块测量运行时间

python - Scikit-Learn 回归模型中的负准确度得分

ruby-on-rails - 为什么在 ApplicationController 上定义为私有(private)的方法可以在派生类的方法内部调用,但不能在派生类本身内部调用?

python - 如何在python中将列表转换为带引号的字符串

javascript - 使用正则表达式从字符串中以特定顺序删除特定单词