Home > Software design >  How to remove line break if it is repeated more than 2 times?
How to remove line break if it is repeated more than 2 times?

Time:09-22

Input: "Some text \n\n\nSome text"

Output: "Some text \n\nSome text"

CodePudding user response:

You could use gsub to replace 3 or more \n's with \n\n:

str = "Some text \n\n\nSome text"

str.gsub(/\n{3,}/, "\n\n")
#=> "Some text \n\nSome text"

or you could use a positive lookbehind to match 1 or more \n that are preceded by \n\n and remove the excess \n's:

str.gsub(/(?<=\n\n)\n /, '')
#=> "Some text \n\nSome text"

CodePudding user response:

my_string = 'Some text \n\n\n\n\nSome text';
while my_string.count('\n') > 2
   my_string = my_string.reverse.sub('\n', '').reverse;
end

puts my_string;
  • Related