2017-04-03 15 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." 
相關問題