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).

6/26/2011 4:14:13 PM

Accepted Answer

Will this do?


Basically it matches a '\n' that is preceded with a character that is not '\r'.

If you want it to detect lines that start with just a single '\n' as well, then try


Which says that it should match a '\n' but only those that is the first character of a line or those that are not preceded with '\r'

There might be special cases to check since you're messing with the definition of lines itself the '$' might not work too well. But I think you should get the idea.

EDIT: credit @Kibbee Using look-ahead s is clearly better since it won't capture the matched preceding character and should help with any edge cases as well. So here's a better regex + the code becomes:

myStr = Regex.Replace(myStr, "(?<!\r)\n", "\r\n");
12/1/2017 11:45:31 AM

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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow