Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to replace all instances of \r not followed by \n with \r\n

How can I replace \r's with \r\n when the \r isn't followed by a \n using Regex ?

The problem

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.

What I tried

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"
like image 458
Barrrdi Avatar asked Jan 02 '17 07:01

Barrrdi


1 Answers

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
like image 61
Wiktor Stribiżew Avatar answered Oct 31 '22 15:10

Wiktor Stribiżew