Remove all empty lines

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.

Leave a Comment