我有一个多行字符串,例如:
"The wolverine is now es-
sentially absent from
the southern end
of its European range."
我想要的是:删除连字符并连接前一行中的单词。 结果,应该是:
"The wolverine is now essentially
absent from
the southern end
of its European range."
答案 0 :(得分:4)
尝试类似
的内容new_string = string.gsub("-\n", "")
这将删除所有短划线,后跟\n
,表示新行
答案 1 :(得分:0)
似乎不是最优化的解决方案,但它在大多数情况下都有效:
text = "The wolverine is now es-\nsentially absent from \nthe southern end\nof its European range."
splitted_text = text.split("-\n")
splitted_text.each_with_index do |line, index|
next_line = splitted_text[index + 1]
if next_line.present?
line << next_line[/\w+/] + "\n"
next_line.sub!(/\w+/, '').strip!
end
end
splitted_text.join
结果
"The wolverine is now essentially\nabsent from \nthe southern end\nof its European range."
答案 2 :(得分:0)
在连接的单词
之后连接包裹的单词和断行的部分text = "The wolverine is now es-\nsentially absent from \nthe southern end\nof its European range."
=> "The wolverine is now es-\nsentially absent from \nthe southern end\nof its European range."
text.gsub(/-\n([^\s]*)\s/,$1+"\n")
=> "The wolverine is now essentially\nabsent from \nthe southern end\nof its European range."
答案 3 :(得分:0)
这就是你需要的:
string.gsub(/(-\n)(\S+)\s/) { "#{$2} \n" }
此代码将删除-\n
以加入“基本上”一词,并在其后添加\n
,返回您的愿望结果:
“狼獾现在已经从它的欧洲范围的南端开始了。\ n”