How can I remove "\r\n" from a string in C#? Can I use a regular expression? How can I remove "\r\n" from a string in C#? Can I use a regular expression? asp.net asp.net

How can I remove "\r\n" from a string in C#? Can I use a regular expression?


You could use a regex, yes, but a simple string.Replace() will probably suffice.

 myString = myString.Replace("\r\n", string.Empty);


The .Trim() function will do all the work for you!

I was trying the code above, but after the "trim" function, and I noticed it's all "clean" even before it reaches the replace code!

String input:       "This is an example string.\r\n\r\n"Trim method result: "This is an example string."

Source: http://www.dotnetperls.com/trim


This splits the string on any combo of new line characters and joins them with a space, assuming you actually do want the space where the new lines would have been.

var oldString = "the quick brown\rfox jumped over\nthe box\r\nand landed on some rocks.";var newString = string.Join(" ", Regex.Split(oldString, @"(?:\r\n|\n|\r)"));Console.Write(newString);// prints:// the quick brown fox jumped over the box and landed on some rocks.