简体   繁体   中英

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. Remove more than 2 line break to be just 1 line break.

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,

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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