I want to convert all newlines in my input string to windows newlines (\r\n). So I want to apply the following mapping:
\r\n -> \r\n
\r -> \r\n
\n -> \r\n
How should this be done?
You could try replacing on the following pattern:
\r(?!\n)|(?<!\r)\n
This would match carriage return which is not followed by newline (i.e. \r but not \r\n CRLF). That failing, it would match just a single newline character, not preceded by carriage return (again, not CRLF).
Usage:
input.replaceAll("\r(?!\n)|(?<!\r)\n", "\r\n");
I would put \r\n, \r, and \n as 3 alternatives separated by |. By putting \r\n first, the other alternatives will not match when there is a \r\n sequence.
input.replaceAll("\r\n|\r|\n", "\r\n")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With