换行后删除多个空格

时间:2014-10-12 03:52:30

标签: ruby string removing-whitespace

我想删除换行符之后的多个空格和制表符,同时保留换行符。示例字符串:

str = "This is a really good morning\n             "

如何删除"\n"后的多个空格?

2 个答案:

答案 0 :(得分:0)

使用正则表达式(String#sub):

str = "This is a really good morning\n             "
str.sub(/[ \t]+\z/, '')  # `[ \t]+\z` matches spaces, tabs at the end of the string.
# => "This is a really good morning\n"

如果您只想删除多个空格(2个或更多):

str.sub(/[ \t]{2,}\z/, '')
# => "This is a really good morning\n"

答案 1 :(得分:0)

问题不明确。这是我所假设的,尽管其他解释是可能的:

  • 如果最后一个非空格字符是字符串的最后一个字符,则返回字符串;

  • 否则,如果最后一个非空白字符后面的空格不包含换行符(“\ n”),则删除尾随空格;

  • 否则在最后一个非空格字符后面的第一个换行符之后删除尾随空格。

这些假设的一个结果是,非空白字符后跟的任何换行符都被视为与非空白字符相同。

这是实现这些假设的一种方式:

def strip_it(str)
  len = str.strip.size
  i = str[len..-1].index("\n")
  i ? str[0,len+i+1] : str.rstrip
end

一些例子:

strip_it "This is a really good morning\n             "
  #=> "This is a really good morning\n"

strip_it "This is a really good morning \n             "
  #=> "This is a really good morning \n"

strip_it "This is a really good morning"
  #=> "This is a really good morning"

strip_it "This is a really good morning\n    cat      "
  #=> "This is a really good morning\n    cat"

strip_it "This is a really good morning\n    cat\n     "
  #=> "This is a really good morning\n    cat\n"

strip_it "This is a really good morning\n    cat \n     "
  #=> "This is a really good morning\n    cat \n"

strip_it "This is a really good morning\n    cat \n dog \n  "
  #=> "This is a really good morning\n    cat \n dog \n"

Lumina,它可能看起来像I'm dancing on the head of a pin,但我详细说明的原因之一是向您展示为什么必须准确说明假设和要求。在实际应用中,当需求不明确时,灾难等待着。