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

Time:08-03

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?

CodePudding user response:

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.

CodePudding user response:

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

CodePudding user response:

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

  •  Tags:  
  • c#
  • Related