简体   繁体   中英

Ruby remove empty lines from string

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

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

挤压(或挤压!)就是这样 - 没有正则表达式。

str.squeeze("\n")

Replace multiple newlines with a single one:

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

or

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

您可以尝试用一个替换所有出现的2个或更多换行符:

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

Originally

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

Updated

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM