TransWikia.com

Group pattern using parenthesis

Mathematica Asked by Jack LaVigne on February 17, 2021

I have a very long list of data. Below is a simplified version

data = {junk1, textHeader, moveTo, text, moveTo, text, junk2, 
  textHeader, moveTo, text, junk3}

I want to extract sequences that start with textHeader followed with moveTo, text and group them.

The result I desire from the above data is

{{textHeader, moveTo, text, moveTo, text}, {textHeader, moveTo, text}}

I can get the first group as follows:

Cases[{data}, {__, head : textHeader, move : moveTo, tex : text, __} :> {head, move, tex}]

which results in

{{textHeader, moveTo, text}}

In order to get multiple occurrences of moveTo and text I tried:

Cases[{data}, {__, head : textHeader, 
   moveNtext : (moveTo, text) .., __} :> {head, moveNtext}]

but I get an error message that says

Syntax::sntxf: "(" cannot be followed by "moveTo,text)".

In addition to overcoming this problem I am only getting out one group and for this case there should be two groups.

One Answer

You can use SequenceCases:

SequenceCases[
    data,
    {textHeader, s:PatternSequence[moveTo, text]..} -> {textHeader, s}
]

{{textHeader, moveTo, text, moveTo, text}, {textHeader, moveTo, text}}

Correct answer by Carl Woll on February 17, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP