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;