Johann Blais
Johann Blais

Reputation: 9469

Regex split a multiline string using \

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.

Upvotes: 0

Views: 1920

Answers (2)

Aliostad
Aliostad

Reputation: 81660

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

Upvotes: 1

Diadistis
Diadistis

Reputation: 12174

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

Upvotes: 1

Related Questions