# Subsequence Search

I need to parse some xml code. I need to extract some values withing pattern elements. I made an example of my trouble. Here is some complicated xml list:

list = {p[1, c, a, p[1, 2], q, b, b, a, p[3, 4], q, b, c, d, a, p[5, 6], q, b, {}, p[7, 8]]};


I need to extract this:

{{1, 2}, {3, 4}, {5, 6}}


I tried to use this pattern:

In[494]:= Cases[list,  p[__, a, p[x_, y_], q, __] :> {x, y}, Infinity]
Out[494]= {{1, 2}}


It doesn't work as I hope. (

I tried some other variants with ReplaceList, SequencePosition, but seems like I can't use it properly.

Mathematica 11.0 TQ

For solution TQ to Jason B. & m_goldberg First of all, I understand that I need to extract most inner list with desired patterns. And then SequenceCases works well. Solution with Partition also works good.

I've compicated the example to show working solutions:

In[614]:=list = {p[1, c, a, p[1, 2], q, b, b, a, p[3, 4], q, b, c, d, a, p[5, 6], q, b, {}, p[7, 8], e, a, p[2], q, e]};
First@Cases[list, p[args : PatternSequence[___, a, _p, q, ___]]:>SequenceCases[{args}, {a, p[x_, y_], q} :> {x, y}], Infinity]
Cases[Partition[List @@ list[[1]], 3, 1], {a, p[x_, y_], q} -> {x, y}]

Out[615]= {{1, 2}, {3, 4}, {5, 6}}
Out[616]= {{1, 2}, {3, 4}, {5, 6}}


I don't know how extensible this is, but it works for your case,

Cases[list,
p[args:PatternSequence[___, a, _p, q, ___]] :> SequenceCases[
{args},
{a, p[x_, y_], q} :> {x, y}
],
Infinity
]
(* {{{1, 2}, {3, 4}, {5, 6}}} *)


This also works for your list, but like Jason B, I don't that is will be applicable to your XML problem.

Cases[Partition[List @@ list[[1]], 3, 1], {a, u : p[_, _], q} -> u]


{p[1, 2], p[3, 4], p[5, 6]}

• My guess is it's like an XMLElement type case... – b3m2a1 May 16 '19 at 1:00
 Cases[list, p[pat : Longest[PatternSequence[___, a, p[_,_], q]], ___] :>
Cases[{pat}, p[x__] :> {x}, All], All]


{{{1, 2}, {3, 4}, {5, 6}}}

• It doesn't work properly: list = {p[1, c, a, p[1, 2], q, b, b, a, p[3, 4], q, b, c, d, a, p[5, 6], q, b, {}, p[7, 8], e, a, p[2], q, e]}; Cases[list, p[pat : Longest[PatternSequence[_, a, _p, q]], ___] :> Cases[{pat}, p[x] :> {x}, All], All] {{{1, 2}, {3, 4}, {5, 6}, {7, 8}, {2}}} – VasilySH May 16 '19 at 17:17
• @VasilySH, try the updated version (using p[_,_] instead of _p inside PatternSequence[...]). – kglr May 16 '19 at 19:00