# Need help in building a pattern [duplicate]

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,
last}]


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?

-

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

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

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:

ReplaceList[list,
{__, {__, 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}

-
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