coder
coder

Reputation: 527

Regular expression to split a string (which contains newline characters) into equal length chunks

I have got a string let's say Test Subject\r\nTest Comments... I want to write a regular expression which would split the string to chunks of n characters say n=6 and the split process should not be affected by newline characters (\r\n).

The code which i have come up with is

string pattern = ".{1," + 6 + "}";
string noteDetails = "Test Subject\r\nTest Comments...";
List<string> noteComments = Regex.Matches(noteDetails, pattern).Cast<Match>().Select(x => x.Value).ToList();`

But the output which i am getting is

Test S
ubject

Test C
omment
s...

The desired output is

Test S
ubject
\r\nTe
st Com
ments.
..

If \r\n is not present then the code works fine. The bottom line is \r\n should also be considered as normal characters.

Thanks in advance

Upvotes: 0

Views: 53

Answers (2)

Austin T French
Austin T French

Reputation: 5131

A second more traditional approach, because Regex is rarely the best choice:

    var stringToSplit = @"Test Subject\r\nTest Comments...";

    var length = stringToSplit.Length;
    var lineLength = 6;

    var lastIndex = 0;
    for(int i = 0; i < length - lineLength ; i+= lineLength)
    {
        lastIndex = i;
        Console.WriteLine(stringToSplit.Substring(i, lineLength));
    }
    if (lastIndex < length)
    {           
        Console.WriteLine(stringToSplit.Substring(lastIndex + lineLength, (length - (lastIndex + lineLength))));
    }

And the output:

Test S
ubject
\r\nTe
st Com
ments.
..

Upvotes: 1

jdweng
jdweng

Reputation: 34421

You do not need regex. Use string methods :

            string input = "Test Subject\nTest Comment";

            string[] results = input.ToCharArray()
                .Where(x => x != '\n')
                .Select((x, i) => new { chr = x, index = i })
                .GroupBy(x => x.index / 6)
                .Select(x => string.Join("", x.Select(y => y.chr)))
                .ToArray();

Upvotes: 1

Related Questions