首页 > 解决方案 > 删除字符串之间的多个换行符并用java中的单个换行符替换

问题描述

我有字符串

String description = a 
\n
\n
\n
\n
\n
b

我想将换行符删除为 1 个换行符。删除超过 2 个换行符,使其成为 1 个换行符。

我试过这个

String descResult = description.replaceAll("([\n]){2,}", "");

但它不起作用。

标签: javaandroidregex

解决方案


除了新行之外,您似乎也有周围的空格,因此您需要使用一个正则表达式,它也可以选择捕获可选空格。试试这个Java代码,

String s = "a \n \n \n \n \n b";
System.out.println("Before: " + s);
System.out.println("After: " + s.replaceAll("( *\n *){2,}", "\n"));

印刷,

Before: a 




 b
After: a
b

推荐阅读