tags:

views:

13680

answers:

5

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 by:

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

But this is inelegant, and would destroy any "\r+\r\n" already in the text (not that it's likely to be there).

+11  A: 

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 = myStr.Replace("(?<!\r)\n", "\r\n");
chakrit
+2  A: 

I guess that "myStr" is an object of type String, in that case, this is not regex. \r and \n are the equivalents for CR and LF.

My best guess is that if you know that you have an \n for EACH line, no matter what, then you first should strip out every \r. Then replace all \n with \r\n.

The answer chakrit gives would also go, but then you need to use regex, but since you don't say what "myStr" is...

Edit:looking at the other examples tells me one thing.. why do the difficult things, when you can do it easy?, Because there is regex, is not the same as "must use" :D

Edit2: A tool is very valuable when fiddling with regex, xpath, and whatnot that gives you strange results, may I point you to: http://www.regexbuddy.com/

neslekkiM
+1  A: 
myStr.Replace("([^\r])\n", "$1\r\n");

$ may need to be a \

Chris Marasti-Georg
A: 

A non-C# solution to the problem might be the unix2dos command.

Jon Ericson
+9  A: 

It might be faster if you use this.

(?<!\r)\n

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

Kibbee