2
$\begingroup$

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!

$\endgroup$

1 Answer 1

5
$\begingroup$

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}}

$\endgroup$
2
  • $\begingroup$ Do you reckon that Shortest[x__] could also work? $\endgroup$
    – LLlAMnYP
    Aug 26, 2018 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, 2018 at 8:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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