2017-04-03 55 views
0

我有一个多行字符串,例如:如何在Ruby中使用换行符连接单词?

"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

这之后的部分是你需要的东西:

string.gsub(/(-\n)(\S+)\s/) { "#{$2} \n" }

此代码将删除-\n加入“基本上”这个词并在其后添加\n,返回您的愿望结果:

“的沃尔弗林现在基本上由\ \ n此nabsent南端\ NOF其欧洲范围\ n”。

4

试着这么做

new_string = string.gsub("-\n", "") 

这将删除所有破折号后面\n,这表明一个新行

+2

为了安全起见,也许's.gsub(/(<= [[?:阿尔法:]]) - \ S * \ n \ S */“”)'。 –

+0

这里有点松懈是件好事。尾随空间经常发生意外。 – tadman

+0

如果正则表达式是'r = /(?<= [[:alpha:]]) - \ s * \ n \ s * /',“狼本质上是es- \ n”.gsub(r,' ')#=>“狼獾现在基本上是”'和'“111-222- \ n3333”.gsub(r,'')#=>“111-222- \ n3333”'(保留中断)。 '(?<= [[:alpha:]])是一个积极的倒序,它要求在连字符前加一个字母。 –

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

CONCAT包裹字和断线的concatened字

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." 
相关问题