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

How to replace \rwith \r\nif \rnot used \nusing Regex?

Problem

I am having problems with a text editor in Windows that I create in that line breaks are added as \ r. As a result, they are not read as line breaks when I open a file in Notepad.

What i tried

I tried searching everywhere (google, stackoverflow, etc.) for this, but could not find what was specifically for what I needed.

Everything I have tried so far does what I do after the first time, but then saves an unnecessary replacement \r, even if it follows them \n.

For reference, this expression:

"\r(?!^\n)", "\r\n"
+4
1

\r(?!\n)

, ^ / \r(?!^\n). \r , (?!\n) , LF .

A # 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
+4

Source: https://habr.com/ru/post/1665495/


All Articles