Max
Max

Reputation: 170

Regex.Replace removes '\r' character in "\r\n"

Here is a simple example

string text = "parameter=120\r\n";
int newValue = 250;

text = Regex.Replace(text, @"(?<=parameter\s*=).*", newValue.ToString());

text will be "parameter=250\n" after replacement. Replace() method removes '\r'. Does it uses unix-style for line feed by default? Adding \b to my regex (?<=parameter\s*=).*\b solves the problem, but I suppose there should be a better way to parse lines with windows-style line feeds.

Upvotes: 1

Views: 634

Answers (3)

Gusdor
Gusdor

Reputation: 14334

Try this:

string text = "parameter=120\r\n";
int newValue = 250;

text = Regex.Replace(text, @"(parameter\s*=).*\r\n", "${1}" + newValue.ToString() + "\n");

Final value of text:

parameter=250\n

Match carriage return and newline explicitly. Will only match lines ending in \r\n.

Upvotes: 1

Amadan
Amadan

Reputation: 198324

Take a look at this answer. In short, the period (.) matches every character except \n in pretty much all regex implementations. Nothing to do with Replace in particular - you told it to remove any number of ., and that will slurp up \r as well.

Can't test now, but you might be able to rewrite it as (?<=parameter\s*=)[^\r\n]* to explicitly state which characters you want disallowed.

Upvotes: 1

Anirudha
Anirudha

Reputation: 32797

. by default doesn't match \n..If you want it to match you have to use single line mode..

(?s)(?<=parameter\s*=).*
 ^

(?s) would toggle the single line mode

Upvotes: 1

Related Questions