How to split a line while saving line endings?

I have a block of text, and I want its lines to not lose \ 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 this?

Accepted answer

string[] lines =  Regex.Split(tbIn.Text, @"(?<=\r\n)(?!$)");
+3
source share
6 answers

The following seems to do the job:

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

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

(?! $) uses a negative lookahead to prevent a match at the end of input and therefore avoids the final line, which is an empty string.

+6

(\n), :

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

: Regex.Replace .

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

- : [^\\] *\\

Regex.Matches(). , (1) . Python map(). , .NET, ; -)

0

, . , , - , API . - ( # ). , , :

string[] lines = tbIn.Text.Split('\n');
for (int i = 0; i < lines.Length; ++i)
{
    lines[i] = lines[i].Replace("\r", "\r\n");
}

... , , ! , . , IndexOf(), "\ r ", . , , , .

, , "\ r\n" , TextBox. , ? ... , ""?

0

You can achieve this with regex. The extension method is used here:

    public static string[] SplitAndKeepDelimiter(this string input, string delimiter)
    {
        MatchCollection matches = Regex.Matches(input, @"[^" + delimiter + "]+(" + delimiter + "|$)", RegexOptions.Multiline);
        string[] result = new string[matches.Count];
        for (int i = 0; i < matches.Count ; i++)
        {
            result[i] = matches[i].Value;
        }
        return result;
    }

I am not sure if this is the best solution. Yours is very compact and simple.

0
source

As always, the advantages of the extension method :)

public static class StringExtensions
{
    public static IEnumerable<string> SplitAndKeep(this string s, string seperator)
    {
        string[] obj = s.Split(new string[] { seperator }, StringSplitOptions.None);

        for (int i = 0; i < obj.Length; i++)
        {
            string result = i == obj.Length - 1 ? obj[i] : obj[i] + seperator;
            yield return result;
        }
    }
}

using:

        string text = "One,Two,Three,Four";
        foreach (var s in text.SplitAndKeep(","))
        {
            Console.WriteLine(s);
        }

Output:

First of all,

Secondly,

Three

Four

0
source

Source: https://habr.com/ru/post/1702430/


All Articles