Removing carriage return/line field from a string

J

John Dalberg

Hi

What's the regex to remove the carriage return/line field from a string?
These can occur multiple times in the string as in xxx\r\n\r\n.
 
S

Sean Hederman

Use
myString = myString.Replace(System.Environment.NewLine, string.Empty);

System.Environment.NewLine is more portable than "\r\n", and Replace is
*far* faster than a regular expression.
 
H

Helge Jensen

John said:
Hi

What's the regex to remove the carriage return/line field from a string?
These can occur multiple times in the string as in xxx\r\n\r\n.

Warning: untested code.

Simple (but possibly a bit expensive):

string RemoveAndNewlineLineFeed(string s) {
char[] lf = {'\r', '\n'};
return string.Join("", string.Split(s, lf));
}

Note that (according to string.Split docs):
RemoveNewlineAndLineFeed("a\rb\nc\r\nd\n\re\r\r\n\r\n").Equals("abcde").
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top