如何同时保持行尾拆分字符串? [英] How to split a string while preserving line endings?

查看:82
本文介绍了如何同时保持行尾拆分字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本块,我想获得它的线条的失去\r和\\\
底。现在,我有以下的(次优代码):

 的String [] =行tbIn.Text.Split('\ N')
。选择(T => t.Replace(\r,\r\\\
)。)ToArray的();



所以我不知道 - ?有没有更好的办法做到这一点。



接受的答案

 的String [] =行Regex.Split (tbIn.Text,@(小于?= \r\\\
)($)!);


解决方案

下面似乎做的工作:

 的String [] =行Regex.Split(tbIn.Text,@(小于?= \r\\\
)(? !$));



(小于?= \r\\\
)采用积极的后向后\\匹配\\r\\\
不消耗它。



(?!$)使用负向前查找,以防止在输入的结束匹配,从而避免了最后一行,这只是一个空字符串。


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)(?!$)");

解决方案

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.

这篇关于如何同时保持行尾拆分字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆