简体   繁体   中英

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"

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM