开发者

Ruby remove empty lines from string

How do i remove empty lines from a string? I have tried some_string = some_string.gsub开发者_Go百科(/^$/, "");

and much more, but nothing works.


Remove blank lines:

str.gsub /^$\n/, ''

Note: unlike some of the other solutions, this one actually removes blank lines and not line breaks :)

>> a = "a\n\nb\n"
=> "a\n\nb\n"
>> a.gsub /^$\n/, ''
=> "a\nb\n"

Explanation: matches the start ^ and end $ of a line with nothing in between, followed by a line break.

Alternative, more explicit (though less elegant) solution:

str.each_line.reject{|x| x.strip == ""}.join


squeeze (or squeeze!) does just that - without a regex.

str.squeeze("\n")


Replace multiple newlines with a single one:

fixedstr = str.gsub(/\n\n+/, "\n") 

or

str.gsub!(/\n\n+/, "\n") 


You could try to replace all occurrences of 2 or more line breaks with just one:

my_string.gsub(/\n{2,}/, '\n')


Originally

some_string = some_string.gsub(/\n/,'')

Updated

some_string = some_string.gsub(/^$\n/,'')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜