Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert newlines to windows newlines [duplicate]

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?

like image 994
ItIsJustMe Avatar asked Dec 12 '25 00:12

ItIsJustMe


2 Answers

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");
like image 180
Tim Biegeleisen Avatar answered Dec 13 '25 13:12

Tim Biegeleisen


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")
like image 40
Sweeper Avatar answered Dec 13 '25 13:12

Sweeper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!