Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all empty lines

Tags:

java

string

regex

I thought that wasn't that hard to do, but I want to remove all empty lines (or lines just containing blanks and tabs in Java) with String.replaceAll.

My regex looks like this:

s = s.replaceAll ("^[ |\t]*\n$", ""); 

But it doesn't work.

I looked around, but only found regexes for removing empty lines without blanks or tabs.

like image 689
reox Avatar asked Nov 08 '10 11:11

reox


People also ask

How do I remove blank lines?

There is also a very handy keyboard shortcut to delete rows (columns or cells). Press Ctrl + – on the keyboard. That's it! Our blank rows are gone now.

How do you delete all empty rows in Word?

Microsoft Office Word does not provide a convenient way to remove empty rows and columns, and you need to remove them by manually select each empty row and column and then delete them one by one. Step 4: In the Rows & Columns group, click Delete Rows or Delete Columns.

How do I remove blank lines in notepad?

First you need to open the file with Notepad++. Once the document is loaded, select Edit > Line Operations > Remove Empty Lines. Voilà, every single blank lines has been deleted.


2 Answers

Try this:

String text = "line 1\n\nline 3\n\n\nline 5"; String adjusted = text.replaceAll("(?m)^[ \t]*\r?\n", ""); // ... 

Note that the regex [ |\t] matches a space, a tab or a pipe char!

EDIT

B.t.w., the regex (?m)^\s+$ would also do the trick.

like image 77
Bart Kiers Avatar answered Oct 12 '22 15:10

Bart Kiers


I don't know the syntax for regular expressions in Java, but /^\s*$[\n\r]{1,}/gm is the regex you're looking for.

You probably write it like this in Java:

s = s.replaceAll("(?m)^\\s*$[\n\r]{1,}", ""); 

I tested it with JavaScript and it works fine.

like image 23
Alin Purcaru Avatar answered Oct 12 '22 13:10

Alin Purcaru