[ACCEPTED]-Regex (C#): Replace \n with \r\n-regex
It might be faster if you use this.
(?<!\r)\n
It basically 8 looks for any \n that is not preceded by 7 a \r. This would most likely be faster, because 6 in the other case, almost every letter matches 5 [^\r], so it would capture that, and then 4 look for the \n after that. In the example 3 I gave, it would only stop when it found 2 a \n, and them look before that to see if 1 it found \r
Will this do?
[^\r]\n
Basically it matches a '\n' that 15 is preceded with a character that is not 14 '\r'.
If you want it to detect lines that 13 start with just a single '\n' as well, then 12 try
([^\r]|$)\n
Which says that it should match a '\n' but 11 only those that is the first character of 10 a line or those that are not preceded with 9 '\r'
There might be special cases to check 8 since you're messing with the definition 7 of lines itself the '$' might not work too 6 well. But I think you should get the idea.
EDIT: credit 5 @Kibbee Using look-ahead s is clearly better 4 since it won't capture the matched preceding 3 character and should help with any edge 2 cases as well. So here's a better regex 1 + the code becomes:
myStr = Regex.Replace(myStr, "(?<!\r)\n", "\r\n");
I was trying to do the code below to a string 2 and it was not working.
myStr.Replace("(?<!\r)\n", "\r\n")
I used Regex.Replace 1 and it worked
Regex.Replace( oldValue, "(?<!\r)\n", "\r\n")
I guess that "myStr" is an object 16 of type String, in that case, this is not 15 regex. \r and \n are the equivalents for 14 CR and LF.
My best guess is that if you know 13 that you have an \n for EACH line, no matter 12 what, then you first should strip out every 11 \r. Then replace all \n with \r\n.
The answer 10 chakrit gives would also go, but then you 9 need to use regex, but since you don't say 8 what "myStr" is...
Edit:looking 7 at the other examples tells me one thing.. why 6 do the difficult things, when you can do 5 it easy?, Because there is regex, is not 4 the same as "must use" :D
Edit2: A 3 tool is very valuable when fiddling with 2 regex, xpath, and whatnot that gives you 1 strange results, may I point you to: http://www.regexbuddy.com/
myStr.Replace("([^\r])\n", "$1\r\n");
$ may need to be a \
0
Try this: Replace(Char.ConvertFromUtf32(13), Char.ConvertFromUtf32(10) + Char.ConvertFromUtf32(13))
0
If I know the line endings must be one of 6 CRLF or LF, something that works for me 5 is
myStr.Replace("\r?\n", "\r\n");
This essentially does the same neslekkiM's answer 4 except it performs only one replace operation 3 on the string rather than two. This is also 2 compatible with Regex engines that don't 1 support negative lookbehinds or backreferences.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.