删除所有空行 [英] Remove all empty lines

查看:111
本文介绍了删除所有空行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为这并不难,但我想用String.replaceAll删除所有空行(或者只包含Java中的空格和制表符的行)。

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.

我的正则表达式如下:

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

但它不起作用。

我环顾四周,但只找到正则表达式,用于删除没有空格或标签的空行。

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

推荐答案

试试这个:

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

请注意正则表达式 [| \ t] 匹配空格,制表符或管道字符!

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

顺便说一下,正则表达式(?m)^ \ s + $ 也可以解决问题。

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

这篇关于删除所有空行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆