Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using regex to delete extra empty lines of a text

Tags:

regex

I have a text like this:

.class
{
   margin:5px;


   border: none;




   font-size: 12px;
}

And then I want to remove extra lines, I use the following regex for that to replace:

/^\s*$/

It selects all empty lines, but what happens? It keeps at least one lines between two other line, I mean, it results in the following text:

.class
{
   margin:5px;

   border: none;

   font-size: 12px;
}

what I need is a regex to remove any space between two lines, and only keeps a newline character, which is something similar to this:

.class
{
   margin:5px;    
   border: none;    
   font-size: 12px;
}

1 Answers

For something that will work on Unix and Windows, use this:

Search: (\r?\n)(?:\r?\n)+

Replace: $1 or \1

Explanation

  • (\r?\n) captures to Group 1 an optional carriage return, and a newline. This allows us to match either Windows-style \r\n sequences or Unix-style \n
  • (?:\r?\n)+ matches one or more additional line breaks
  • We replace the match with the content of Group 1
like image 152
zx81 Avatar answered Sep 21 '25 16:09

zx81