Reputation: 143
I have a String like this:
String orginal = "this is for test hello\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n" +
"\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nhello" +
"\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nhello";
The user press 'enter' a lot of time when input content in text area, so in java, it change to a lot of '\r\n'. I want to change it to:
String newStr = "this is for test hello\r\nhello\r\nhello"
How can I keep only one \r\n
Upvotes: 1
Views: 517
Reputation: 136002
Generic solution (LF - UNIX, CR- Mac, CRLF - Windows) could be like this
String newStr = original.replaceAll("(\r\n|\r|\n)+", "$1");
Upvotes: 0
Reputation: 5377
This ought to do it...
String newStr = original.replaceAll("(\r\n)+", "\r\n");
You might also want to consider using the line.separator
system property instead of hard coding \r\n
, since this may be different on other platforms. For instance Unix just uses a single line feed \n
. This would be more portable...
final String NEWLINE = System.getProperty("line.separator");
String newStr = original.replaceAll("(" + NEWLINE + ")+", NEWLINE);
Upvotes: 5