# How to split a list based on pattern

I am trying to split a list based on pattern of some elements of the list.

list = {a^(-1-x1),b^(-x2), (a+b)^(-x3), (1-a)^(-1+x4),(1-b)^(-1), (1+a b)}


I want to split the list into two based on a pattern given as a list. I am using SequenceCases to achieve that. However it does not work for more than two patterns given as a list.

 pattern = {Power[a,x_],Power[b,y_],Power[1-a,z_]};
list1=SequenceCases[list,pattern]



whose output (expected) should be

 list1={a^(-1-x1),b^(-x2), (1-a)^(-1+x4)}
list2={(a+b)^(-x3),(1-b)^(-1), (1+a b)}


Note that I do not want to split the list based on position of elements, rather based on certain pattern/members of the list.

Additionally I wanted to ask if there is any easier way to find all the elements which have negative exponent (assuming all non-numeric variables in the exponent are 0.).

 {a^(-1-x1), (1-a)^(-1+x4), (1-b)^(-1)}


I can perform a Do loop through the elements of the list, however it would be nice to know if there is any better alternative.

• Might I recommend: GroupBy[list, MatchQ[#, Alternatives @@ pattern] &] That groups into a True group that matches the pattern and a False group that does not. You can access via result[True] or Lookup[result, True] Feb 18 at 1:21

If you have to use SequenceCases and pattern:

list1 = Flatten @ SequenceCases[list, {Alternatives @@ pattern}]

{a^(-1 - x1), b^-x2, (1 - a)^(-1 + x4)}

list2 = Flatten @ SequenceCases[list, {Except[Alternatives @@ pattern]}]

{(a + b)^-x3, 1/(1 - b), 1 + a b}


Otherwise, you can use Cases:

list1b = Cases[list, Alternatives @@ pattern]

{a^(-1 - x1), b^-x2, (1 - a)^(-1 + x4)}

list2b = Cases[list, Except[Alternatives @@ pattern]]

{(a + b)^-x3, 1/(1 - b), 1 + a b}


For both methods, we can use an alternative simpler pattern top get the same result:

pattern2 = Power[a | b | (1 - a), _];

Flatten @ SequenceCases[list, {pattern2}]

Cases[list, pattern2]

% == %% == list1

True

Flatten @ SequenceCases[list, {Except @ pattern2}]

Cases[list, Except @ pattern2]

% == %% == list2

True


"to find all the elements which have negative exponent (assuming all non-numeric variables in the exponent are 0.)."

Cases[list, _^(a_ + _.) /; Negative[a /. _Symbol -> 0], All]

 {a^(-1 - x1), (1 - a)^(-1 + x4), 1/(1 - b)}


Try this:

lst = {a^(-1 - x1),
b^(-x2), (a + b)^(-x3), (1 - a)^(-1 + x4), (1 - b)^(-1), (1 + a b)};

lst1 = lst /. Power[y_, x__] /; y == a || y == b || y == c -> Nothing
lst2 = Complement[lst, lst1]

(*  {(a + b)^-x3, (1 - a)^(-1 + x4), 1/(1 - b), 1 + a b}

{a^(-1 - x1), b^-x2}   *)


Have fun!