Ruby:如何剥离字符串并获取删除的空格?

标签 ruby string whitespace strip

给定一个字符串,我想剥离它,但我想删除前后的空格。例如:

my_strip("   hello world ")   # => ["   ", "hello world", " "]
my_strip("hello world\t ")    # => ["", "hello world", "\t "]
my_strip("hello world")       # => ["", "hello world", ""]

您将如何实现 my_strip

最佳答案

解决方案

def my_strip(str)
  str.match /\A(\s*)(.*?)(\s*)\z/m
  return $1, $2, $3
end

测试套件 (RSpec)

describe 'my_strip' do
  specify { my_strip("   hello world ").should      == ["   ", "hello world", " "]     }
  specify { my_strip("hello world\t ").should       == ["", "hello world", "\t "]      }
  specify { my_strip("hello world").should          == ["", "hello world", ""]         }
  specify { my_strip(" hello\n world\n \n").should  == [" ", "hello\n world", "\n \n"] }
  specify { my_strip(" ... ").should                == [" ", "...", " "]               }
  specify { my_strip(" ").should                    == [" ", "", ""]                   }
end

关于Ruby:如何剥离字符串并获取删除的空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7371190/

相关文章:

ruby-on-rails - Heroku 上 Gemfile 中的自定义 Ruby Gem

java - String to float/double 解析

java - 如何用 HashMap 中的字符替换字符串?

HTML 等同于......确实会中断;

java - 如何在java中扫描文本时删除空格

ruby-on-rails - 遍历哈希数组并执行 titleize 并返回数组

html - Ruby gem 快速验证部分 HTML 片段?

ruby - 懒洋洋地逐段阅读文件

string - 搜索多个子字符串的字符串的好算法是什么?

javascript - 从模板字符串中渲染空白