Bimo
Bimo

Reputation: 6627

In C#, Remove Blank lines only at end of multiline string

I have a multiline string that looks something like this:

string line = "one two three.    \r\n\r\n     ## ENDr\n\r\n "

I was thinking I could keep all the blank lines before #END and remove the blank lines at the end of the string using this expression:

string text2 = Regex.Replace(line, @"(\s*\r\n)+$", "");

However, it leads to an infinite loop on the Regex.Replace for some reason when i load a similar file into string line...

Any Ideas?

Upvotes: 1

Views: 558

Answers (3)

Jason
Jason

Reputation: 33

string.TrimEnd() is your best bet. New lines and whatnot are characters as far as the string type is concerned, so TrimEnd() will only cull whitespace after the final character

Upvotes: -1

lee-m
lee-m

Reputation: 2267

You can use TrimEnd to remove all whitespace characters from the end of a string. Since newlines are considered whitespace, this will chop them off. Any whitespace in the middle will be ignored.

Upvotes: 4

Bimo
Bimo

Reputation: 6627

string text2 = Regex.Replace(text, @"[\s\n\r]+$", "");
text2 += "\r\n";

Upvotes: -1

Related Questions