c# – Regex split a multiline string using \ – Education Career Blog

I have tried approximately every possible combination of RegexOptions.MultiLine and escaped backslashes in order to split a text using \ as a separator.

I have this text:

The quick brown
Fox jumps\
Over the
Lazy dog\

I want to split it into

The quick brown
Fox jumps\

and

Over the
Lazy dog\

I have tried so far (together with a call to the Split method of the Regex):

Regex regexSplit = new Regex(@"\\$", RegexOptions.Multiline);
Regex regexSplit = new Regex(@"\$", RegexOptions.Multiline);
Regex regexSplit = new Regex(@"\\$", RegexOptions.Singleline);
Regex regexSplit = new Regex(@"\$", RegexOptions.Singleline);
Regex regexSplit = new Regex(@"\\$");
Regex regexSplit = new Regex(@"\$");

Every time I get back the complete original string.
Could you give me a hand please?

Thank you in advance.

EDIT: I removed an extra space.
The reason why I need to use a Regex is because a \ might be inside a match enclosed in “” or ”.
This is why I need to match on end of line as well.

I must add that \\$ works when I test the expression using RegexBuddy and the same input text.

,

You have an extra space at “Fox jumps\ ” so @"\\$" won’t match. Either remove the space or use @"\\" to split. You can also check for spaces @"\\\s*$".

This one should do the trick :

var results = Regex.Split(subject, @"\\\s*$", RegexOptions.Multiline);

,

Why not this simple string split:

        string s = "The quick brown\r\nFox jumps\\\\r\n Over the\r\nLazy dog\\";
    s.Split(new string { "\\\r\n" }, StringSplitOptions.RemoveEmptyEntries);

Leave a Comment