C# – Regex (C#): Replace \n with \r\n


How can I replace lone instances of \n with \r\n (LF alone with CRLF) using a regular expression in C#?

Sorry if it's a stupid question, I'm new to Regex.

I know to do it using plan String.Replace, like:

myStr.Replace("\n", "\r\n");
myStr.Replace("\r\r\n", "\r\n");

However, this is inelegant, and would destroy any "\r+\r\n" already in the text (although they are not likely to exist).

Best Solution

It might be faster if you use this.


It basically looks for any \n that is not preceded by a \r. This would most likely be faster, because in the other case, almost every letter matches [^\r], so it would capture that, and then look for the \n after that. In the example I gave, it would only stop when it found a \n, and them look before that to see if it found \r