字符串中的新换行字符串

时间:2013-12-15 23:38:08

标签: ruby regex

我有这个字符串:

"“It's hard to beat a person who never gives up.”\n    ―\n    Babe Ruth"

我已经成功剥离了这个:

“It's hard to beat a person who never gives up.”\n ―\n Babe Ruth

使用此正则表达式:

/^"(.*)"/

现在我需要删除两个换行符并删除多余的空格。这就是我想要回归的内容:

=> "It's hard to beat a person who never gives up." - Babe Ruth 

有人可以给我一个提示吗?

3 个答案:

答案 0 :(得分:2)

我不是100%明确你所要求的,但我你想要这样的东西:

s = "“It's hard to beat a person who never gives up.”\n    ―\n    Babe Ruth"
s.gsub(/\s+/, " ")
# => "“It's hard to beat a person who never gives up.” ― Babe Ruth"

这就是说,“用空格替换任何一个或多个空白字符。”

答案 1 :(得分:0)

使用String#squeeze删除连续字符,使用String#gsub删除换行符:

string = "\“It's hard to beat a person who never gives up.\”\n    ―\n    Babe Ruth'"

string.squeeze(' ').gsub("\n", '')                                                                                              
#=> "“It's hard to beat a person who never gives up.” ― Babe Ruth'"

http://ruby-doc.org/core-2.0.0/String.htm

答案 2 :(得分:0)

根据您想要的最终结果,有不同的方法可以解决这个问题。

作为一个起点:

# encoding: UTF-8

puts "“It's hard to beat a person who never gives up.”\n    ―\n    Babe Ruth".gsub(/\s\s+/, ' ')
# >> “It's hard to beat a person who never gives up.” ― Babe Ruth

您的示例结果没有卷曲引号或连字符(您的示例有em-dash):

puts "“It's hard to beat a person who never gives up.”\n    ―\n    Babe Ruth".gsub(/\s\s+/, ' ').tr('“”―', '""-')
# >> "It's hard to beat a person who never gives up." - Babe Ruth