seal seal - 1 year ago 50
Java Question

how can I remove multiple new line and space(white char) from a string?

A String looks like this :

" I am seal \n\n \t where are we? "
. and the printed version

I am seal

where are we?

I want to make the string like :
"I am seal\nwhere are we?"

I am seal
where are we?

I am removing the new line with
"[\r\n]+", "\n"
this regex but the problem is when I am trying to remove the white space it also remove the newline. I have used


Also white space from the beginning of the second line also be removed. It should not be consecutive.

How can I achieve this in Java ?

Thank you.

Answer Source


Catching all initial white-spaces (caret ^ asserts that we are at beginning of line) and other consecutive spaces:

(^\\s+|[\\t\\f ](?=[\\t\\f ])|[\\t\\f ]$)

Replace it with nothing (multi-line modifier is important to be on):

String str = "   I am   seal \n\n  \t   where are we? ";
String result = str.replaceAll("(?m)(^\\s+|[\\t\\f ](?=[\\t\\f ])|[\\t\\f ]$)", "");

Live demo