How do I replace multiple \n‘s with just one? So if a user enters
blah
blahdy blah
blah blah
I want it to end up looking like.
blah
blahdy blah
blah blah
I know I could loop through with a while() but would rather use a regular expression, since I believe it’s more efficient.
This worked for me:
As others have said, it replaces each occurrence of one or more consecutive newline characters (
\n+) with just one.The
geffects a “global” replace, meaning it replaces all matches in the string rather than just the first one.Edit: If you want to take into account other operating systems’ line ending styles as well (e.g.,
\r\n), you could do a multi-step replace:OR (thanks to Renesis for this idea):
If you know in advance what sort of text you’re dealing with, the above is probably overkill as it carries am obvious performance cost.