Removing a large space from a text in Java

java, regex, string

Solution

There is a simple trick, replace `\\s` with a negated character class :`[^\\S\\r\\n]` where `\\S` is "all that is not a white character".

Note: if you want to preserve a space between words, you must change your replacement string to `" "`

Example:

String tmp = input.replaceAll("[^\\S\\r\\n]+", " ");

Note: You can use a class intersection too: `[\\s&&[^\\r\\n]]`

Problem

I am trying to remove a big whitespace and retain the CR and LF character in a String. This string is generated by Lotus Domino API. This is basically an eml file converted to text by Lotus API. When I do the below : ``` String input = "This is a test string\r\nThis is another test string"; String tmp = input.replaceAll("\\s+", ""); System.out.println(tmp); Output: This is a test string This is another test string Desired Output : This is a test string\r\nThis is another test string ``` Removing whitespace is not an issue but I am not able to retain the carriage return and linefeed in the String. Any help on this is greatly appreciated.

Original source