Skip to content
Advertisement

Remove all empty lines

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.

Advertisement

Answer

Try this:

String text = "line 1nnline 3nnnline 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.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement