Ruby or regex to break redundant lines

How would you do it:

Dear fred



How are you?






Regards
John

In it:

Dear fred

How are you?

Regards
John

Note. Single and double breaks are allowed, but nothing more. For example, we want to go from:

"Dear Fred \ n \ n \ n \ nHow are you? \ N \ n \ n \ n \ n \ n \ nRegards \ nJohn"
to
"Dear Fred \ n \ nHow are you? \ N \ nRegards \ nJohn"

But you should also work for "\ r \ n".

+3
source share
3 answers

Something like that?

s.gsub /(\r?\n){3,}/, '\1\1'

It seems to at least work with your example:

irb(main):060:0> s
=> "Dear Fred\n\n\n\nHow are you?\n\n\n\n\n\n\nRegards\nJohn"
irb(main):061:0> s.gsub /(\r?\n){3,}/, '\1\1'
=> "Dear Fred\n\nHow are you?\n\nRegards\nJohn"
+2
source

Replace

(\r\n|\n|\r)\1+

with

\1

Where \1refers to the back link. I believe that in ruby ​​this is done through $1.

+2
source
str.gsub!(/\n{3,}/, "\n\n")
str.gsub!(/(\r\n){3,}/, "\r\n\r\n")

/\n {3,}/ (\n). . \r\n.

["\n", "\r\n"].each{|lb| str.gsub!( /(#{lb}){3,}/, lb*2 )}

.

+1

Source: https://habr.com/ru/post/1766557/


All Articles