Remove all empty lines

后端 未结 7 1619
误落风尘
误落风尘 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 17:52

    I'm not a day-to-day Java programmer, so I'm surprised there isn't a simpler way to do this in the JDK than a regex.

    Anyway,

    s = s.replaceAll("\n+", "\n");
    

    would be a bit simpler.

    Update:

    Sorry I missed that you wanted to also remove spaces and tabs.

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

    Would work if you have consistent newlines. If not, you may want to consider making them consistent. E.g.:

    s = s.replaceAll("[\n\r]+", "\n");
    s = s.replaceAll("\n[ \t]*\n", "\n");
    

提交回复
热议问题