views:

54

answers:

2

Hi all,

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.

+1  A: 

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);
Diadistis
Thanks, I removed the extra space.
Johann Blais
It is working! I must add that I am not convinced that there is whitespace between the \ and the end of line in that case. Thank you for your help anyway!
Johann Blais
+1  A: 

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);
Aliostad
He might be interested to split only if \ is at the end of line.
Diadistis
@Diadistis: that's right, I edited my message.
Johann Blais
See my update..
Aliostad
This way you are not taking into account all the possible EOL combinations like `\r` and `\n` but only the windows-style `\r\n`. Regex `$` is much safer to use.
Diadistis