<p>How can I replace lone instances of \n with \r\n (LF alone with CRLF) using a regular expression in C#?</p>
<p>I know to do it using plan <code>String.Replace</code>, like:</p>
<pre><code>myStr.Replace(&quot;\n&quot;, &quot;\r\n&quot;);
myStr.Replace(&quot;\r\r\n&quot;, &quot;\r\n&quot;);
</code></pre>
<p>However, this is inelegant, and would destroy any &quot;\r+\r\n&quot; already in the text (although they are not likely to exist).</p>

Will this do?
```
```
[^\r]\n
```
```
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
```
```
([^\r]|$)\n
```
```
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");
```
```