Remove empty line from a multi-line string with Java
Use regex (?m)^[ \t]*\r?\n"
to remove empty lines:
log.info msg.replaceAll("(?m)^[ \t]*\r?\n", "");
To remain only 1 line use [\\\r\\\n]+
:
log.info text.replaceAll("[\\\r\\\n]+", "");
If you want to use the value later, then assign it
text = text.replaceAll("[\\\r\\\n]+", "");
Your current attempt seems very much on the right track, and I think the logic you want is to replace two or more newlines with just a single newline:
output = msg.replaceAll("(\r?\n)(?:\r?\n){1,}", "$1");
The trick here, to capture the actual newline type being used (\n
for Linux or \r\n
for Windows), is to capture a single \r?\n
first, followed then by at least one more newline.