4
$\begingroup$

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}}
$\endgroup$

3 Answers 3

4
$\begingroup$

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}}} *)
$\endgroup$
2
$\begingroup$

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

$\endgroup$
1
  • $\begingroup$ My guess is it's like an XMLElement type case... $\endgroup$ Commented May 16, 2019 at 1:00
0
$\begingroup$
 Cases[list, p[pat : Longest[PatternSequence[___, a, p[_,_], q]], ___] :> 
    Cases[{pat}, p[x__] :> {x}, All], All]

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

$\endgroup$
2
  • $\begingroup$ 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}}} $\endgroup$ Commented May 16, 2019 at 17:17
  • $\begingroup$ @VasilySH, try the updated version (using p[_,_] instead of _p inside PatternSequence[...]). $\endgroup$ Commented May 16, 2019 at 19:00

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.