Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

This question already has an answer here:

Suppose I have the following list:

list = {w, r, {f, first, t, y}, {a, y}, last, {k, r, first, e}, m, e, last, r, t}

I am expecting this

Cases[list, {__, {__, first, x__}, y__, last, __} :> {{first, x}, y, 

to result in this

(*{{{first, t, y}, {a, y}, last}, {{first, e}, m, e, last}}*)

and this

Cases[Flatten@list, {__, first, x__, last, __} :> {first, x, last}]

to result in this

(*{{first, t, y, a, y, last}, {first, e, m, e, last}}*)

but the results for both are {}.

How can I build a suitable pattern to get the desired results?

share|improve this question

marked as duplicate by m_goldberg, ubpdqn, Michael E2, Sjoerd C. de Vries, RunnyKine Jul 20 '14 at 15:56

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

This should probably be marked as a duplicate of: (23454) – Mr.Wizard Jul 20 '14 at 2:15
up vote 2 down vote accepted

Cases is looking for matches within the input expression, given the default levelspec of {1}, or a single match to the entire expression if you use levelspec {0}. Instead you need multiple matches for the entire expression for which you can use ReplaceList:

  {__, {__, first, x__}, y : Except[last] .., last, __} :>
   {{first, x}, y, last}
{{{first, t, y}, {a, y}, last}, {{first, e}, m, e, last}}

Note that I needed to change the pattern to y : Except[last] .. otherwise you will also match this:

{{first, t, y}, {a, y}, last, {k, r, first, e}, m, e, last}
share|improve this answer
thanks a lot. is there any way to get the same result using Cases? – Algohi Jul 20 '14 at 2:22
@Algohi Not in any practical way of which I am aware. – Mr.Wizard Jul 20 '14 at 2:25

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