How to split a string while preserving line endings?

后端 未结 6 1245
谎友^
谎友^ 2021-01-01 06:02

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):

<         


        
6条回答
  •  悲&欢浪女
    2021-01-01 06:53

    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.

提交回复
热议问题