Gandalf StormCrow
Gandalf StormCrow

Reputation: 26202

Slightly better way of removing new lines

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 :

Upvotes: 1

Views: 77

Answers (2)

Uri Agassi
Uri Agassi

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

cypheon
cypheon

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

Related Questions