简体   繁体   English

删除字符串之间的多个换行符并用java中的单个换行符替换

[英]Remove multiple line breaks between string and replace with single line breaks in java

I have string我有字符串

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

I want to remove the line break to be just 1 line break.我想将换行符删除为仅 1 个换行符。 Remove more than 2 line break to be just 1 line break.删除超过 2 个换行符只是 1 个换行符。

I have tried this我试过这个

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

but it doesn't work.但它不起作用。

In addition to new lines, you seem to be having surrounding spaces too, so you need to use a regex that optionally captures optional spaces too.除了新行之外,您似乎也有周围的空格,因此您需要使用一个正则表达式,它也可以选择捕获可选空格。 Try this Java code,试试这个 Java 代码,

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

Prints,印刷,

Before: a 




 b
After: a
b

试试吧,替换一定是\\n

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM