Ruby remove empty lines from string

后端 未结 5 1911
囚心锁ツ
囚心锁ツ 2021-02-03 10:51

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

and much more, but nothing works.

相关标签:
5条回答
  • 2021-02-03 11:03

    Replace multiple newlines with a single one:

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

    or

    str.gsub!(/\n\n+/, "\n") 
    
    0 讨论(0)
  • 2021-02-03 11:04

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

    str.squeeze("\n")
    
    0 讨论(0)
  • 2021-02-03 11:04

    Originally

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

    Updated

    some_string = some_string.gsub(/^$\n/,'')
    
    0 讨论(0)
  • 2021-02-03 11:16

    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
    
    0 讨论(0)
  • 2021-02-03 11:17

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

    my_string.gsub(/\n{2,}/, '\n')
    
    0 讨论(0)
提交回复
热议问题