简体   繁体   English

Ruby从字符串中删除空行

[英]Ruby remove empty lines from string

How do i remove empty lines from a string? 如何从字符串中删除空行? I have tried some_string = some_string.gsub(/^$/, ""); 我试过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/,'')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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