How to replace multiple newlines in a row with one newline using Ruby

后端 未结 9 840
陌清茗
陌清茗 2021-02-05 03:42

I have a script written in ruby. I need to remove any duplicate newlines (e.g.)

\\n
\\n
\\n

to

\\n

My current

相关标签:
9条回答
  • 2021-02-05 04:18

    This works for me:

    #!/usr/bin/ruby
    
    $s = "foo\n\n\nbar\nbaz\n\n\nquux";
    
    puts $s
    
    $s.gsub!(/[\n]+/, "\n");
    
    puts $s
    
    0 讨论(0)
  • 2021-02-05 04:19

    You need to match more than one newline up to an infinite amount. Your code example will work with just a minor tweak:

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

    For example:

    str = "this\n\n\nis\n\n\n\n\na\ntest"
    str.gsub!(/\n+/, "\n")  # => "this\nis\na\ntest"
    
    0 讨论(0)
  • 2021-02-05 04:20

    Ruby needs the backslashes escaped differently than you have provided.

    str.sub!("\\\\n+\\\\n","\\\\n")
    

    http://www.ruby-forum.com/topic/176239

    0 讨论(0)
提交回复
热议问题