I have a list:

lis = {a, b, c, d, e, f, a, b, k, m, n, e, a, b, d}

and would like to create a list whose elements are those between each occurrence of {a, b} and {e}, which gives:

res = {{c, d}, {k, m, n}}

Thank you very much for ideas!


You can use SequenceCases or ReplaceList:

SequenceCases[lis, {a, b, x : Except[e] .., e} :> {x}]

{{c, d}, {k, m, n}}

ReplaceList[lis, {___, a, b, x : Except[e] .., e, ___} :> {x}]

{{c, d}, {k, m, n}}

  • $\begingroup$ Do you reckon that Shortest[x__] could also work? $\endgroup$ – LLlAMnYP Aug 26 '18 at 7:54
  • $\begingroup$ @LLlAMnYP, that's what I first tried. SequenceCases[lis, {a, b, Shortest[x__], e} :> {x}] gives, somehow, {{c, d, e, f, a, b, k, m, n}}. $\endgroup$ – kglr Aug 26 '18 at 8:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.