3

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?

m_goldberg
  • 107,779
  • 16
  • 103
  • 257
Basheer Algohi
  • 19,917
  • 1
  • 31
  • 78

1 Answers1

2

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}
Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371