3

How can I split a string by '-' and '>' and not by "->"?

I would like to split the string below:

AAA-BBB->CCC>DDD

and get the result equal to:

{ "AAA", "BBB->CCC", "DDD" }
Dmitry
  • 13,797
  • 6
  • 32
  • 48
Jakub Bielawa
  • 144
  • 2
  • 8
  • Not a duplicate. This is splitting by a single character delimiter, except when that character is part of a multi-part string. – jessehouwing Jan 07 '16 at 21:32

1 Answers1

4

The following example uses a regular expression with lookahead and lookbehind rules to split a string based on '-' or '>' but not '->':

string input = "AAA-BBB->CCC>DDD";
var regex = new Regex("-(?!>)|(?<!-)>");
var split = regex.Split(input);
// split = { "AAA, "BBB->CCC", "DDD" }
RogerN
  • 3,761
  • 11
  • 18
  • 2
    I do feel this is slightly easier to read though: `Regex.Split(input, "(?!->)-|>(?<!->)");` It does the same. – jessehouwing Jan 07 '16 at 21:30
  • Online regex testers may not handle this regex correctly because of the lookbehind rule, which is not supported by Javascript. It will work correctly in C#, though. – RogerN Jan 07 '16 at 21:36