Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

regex

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

like image 208
dbkk Avatar asked Aug 27 '08 19:08

dbkk


People also ask

Does C have regex?

The expression can be used for searching text and validating input. Remember, a regular expression is not the property of a particular language. POSIX is a well-known library used for regular expressions in C.

Is regex a standard library in C?

C++11 now finally does have a standard regex library - std::regex.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).

What is pattern matching in C language?

Pattern matching in C− We have to find if a string is present in another string, as an example, the string "algorithm” is present within the string "naive algorithm". If it is found, then its location (i.e. position it is present at) is displayed.


1 Answers

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

like image 62
Kibbee Avatar answered Sep 23 '22 16:09

Kibbee