Reputation: 26202
I've got a text/string that contains multiple newlines. Like in the example below :
"This is a test message : \n \n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
"
I can gsub all \n
with space and remove them all. How can I do the following :
\n
, leave only two newlines in the text?Upvotes: 1
Views: 77
Reputation: 37409
If you want to remove all but the first two newlines you can use the block passed to gsub
:
hits = 0
text.gsub(/\n/) { (hits = hits + 1) > 2 ? '' : "\n" }
# => "This is a test message : \n \n "
Upvotes: 1
Reputation: 1023
You can replace any sequences of three or more newlines with nothing in between, by using the following regex (assuming s
contains your string):
s.gsub /\n\n+/, "\n\n"
If you want to allow any amount of interleaving space characters between the newlines and remove that as well, better use:
s.gsub /\n *(\n *)+/, "\n\n"
Upvotes: 1