Remove all empty lines

后端 未结 7 1634
误落风尘
误落风尘 2020-11-27 17:22

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 look

7条回答
  •  眼角桃花
    2020-11-27 18:17

    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.

提交回复
热议问题