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

后端 未结 9 845
陌清茗
陌清茗 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条回答
  • Try This It Worked for me:

    s = test\n\n\nbar\n\n\nfooo 
    
    s.gsub("\n\n", '')
    
    0 讨论(0)
  • 2021-02-05 04:02

    Use the more idiomatic String#squeeze instead of gsub.

    str = "a\n\n\nb\n\n\n\n\n\nc"
    str.squeeze("\n") # => "a\nb\nc"
    
    0 讨论(0)
  • 2021-02-05 04:04

    Simply calling split will also trim out all of your whitespace.

    You need to pass \n to split

    >> "one   ok \ntwo\n\nthree\n".split(/\n+/).join("\n")
    => "one  ok \ntwo\nthree"
    
    0 讨论(0)
  • 2021-02-05 04:04

    Additionally, also works with

    • spaces on blank lines
    • n number of back to back blank lines

    str.gsub! /\n^\s*\n/, "\n\n"

    where,

    • \n is of course newline
    • \s is space
    • denotes 1 or more spaces along when used after \s
    0 讨论(0)
  • 2021-02-05 04:05

    Simply splitting and recombining the lines will give the desired result

    >> "one\ntwo\n\nthree\n".split.join("\n")
    => "one\ntwo\nthree"
    

    Edit: I just noticed this will replace ALL whitespace substrings with newlines, e.g.

    >> "one    two three\n".split.join("\n")
    => "one\ntwo\nthree"
    

    First check that this is what you want!

    0 讨论(0)
  • 2021-02-05 04:06

    are you sure it shouldn't be /\n\n\n/, "\n" that what you seem to be wanting in your question above.

    also, are you sure it's not doing a windows new-line "\r\n"?

    EDIT: Additional info

    Per Comment

    "The amount of newlines can change. Different lines have between 2 and 5 newlines."

    if you only want to hit the 2-5 lines try this

    /\n{2,5}/, "\n"
    
    0 讨论(0)
提交回复
热议问题