How can I replace \r
's with \r\n
when the \r
isn't followed by a \n
using Regex ?
I'm having problems with a text editor on Windows I'm creating in that line breaks are being added as \r. As a result they are not being read as line breaks when I open the file in Notepad.
I've tried looking everywhere (google, stackoverflow, etc) for this, but have been unable to find something that is specifically for what I'm after.
Everything I've tried so far does what I'm after the first time but it then keeps unnecessarily replacing \r
's even if they're followed by a \n
.
For reference, this is the expression:
"\r(?!^\n)", "\r\n"
You need to use
\r(?!\n)
That is, remove the ^
start of string/line modifier from your \r(?!^\n)
expression. The \r
will match a carriage return and the (?!\n)
will fail the match if there is an LF immediately to the right of it.
A C# demo:
var s = "Line1\rLine2\r\nLine3";
var res = Regex.Replace(s, "\r(?!\n)", "\r\n");
Console.WriteLine(res.Replace("\r","CR").Replace("\n","LF\n"));
// => Line1CRLF
// Line2CRLF
// Line3
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