Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string while preserving line endings?

I have a block of text and I want to get its lines without losing the \r and \n at the end. Right now, I have the following (suboptimal code):

string[] lines = tbIn.Text.Split('\n')
                     .Select(t => t.Replace("\r", "\r\n")).ToArray();

So I'm wondering - is there a better way to do it?

Accepted answer

string[] lines =  Regex.Split(tbIn.Text, @"(?<=\r\n)(?!$)");
like image 456
Dmitri Nesteruk Avatar asked Oct 28 '25 03:10

Dmitri Nesteruk


1 Answers

The following seems to do the job:

string[] lines =  Regex.Split(tbIn.Text, @"(?<=\r\n)(?!$)");

(?<=\r\n) uses 'positive lookbehind' to match after \r\n without consuming it.

(?!$) uses negative lookahead to prevent matching at the end of the input and so avoids a final line that is just an empty string.

like image 199
codybartfast Avatar answered Oct 29 '25 19:10

codybartfast



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!