4
$\begingroup$

For example, the Table have follows structure:

Data = {
  {userid , 1 , brith , 24},
  {math , 90, art , 96, sport, 72 , econmic , 98},
  {userid , 2 , brith, 23},
  {math , 80 , art , 86, sport , 92 , econmic , 92},
  {userid , 3, brith , 25},
  {math , 90 , art, 76 , sport , 82 , econmic, 99},
  {userid, 1, phonenumber , 9157678481},
  {country, UK},
  {userid , 2, phonenumber, 9237678481},
  {country , USA}
  }

My question is how to use regular expressions to extract useid, 1 's data.

Expect result is

{{userid , 1 , brith , 24},
{math , 90, art , 96, sport, 72 , econmic , 98},
{userid, 1, phonenumber , 9157678481},
{country, UK}}

Any comments very much appreciate!

$\endgroup$
4
  • 2
    $\begingroup$ how about Join @@ Select[#[[1, 2]] == 1 &]@Split[Data, #[[1]] == userid &]? $\endgroup$
    – kglr
    Dec 1, 2021 at 9:41
  • 2
    $\begingroup$ Here is another possibility using pattern: Flatten[Cases[Partition[Data, 2], {{userid, 1, __}, {__}}], 1] $\endgroup$ Dec 1, 2021 at 10:00
  • $\begingroup$ All works, thanks to all comments! $\endgroup$
    – lumw
    Dec 1, 2021 at 11:48
  • $\begingroup$ I see, __ is the BlankSequence. $\endgroup$
    – lumw
    Dec 1, 2021 at 12:32

1 Answer 1

7
$\begingroup$

SequenceCases

SequenceCases[data, p : {{_, 1, __}, _} :> Sequence @@ p]

enter image description here

Split + Select

Join @@ Select[#[[1, 2]] == 1 &] @ Split[data, #[[1]] == userid &]

enter image description here

Split + Cases

Cases[p : {{_, 1, __}, __} :> Sequence @@ p] @ Split[data, #[[1]] == userid &]

enter image description here

$\endgroup$
4
  • $\begingroup$ Owesome! How did you do that! SequenceCases is very helpful. if I want remove the expect result like {{userid , 1 , brith , 24}, {math , 90, art , 96, sport, 72 , econmic , 98}, {userid, 1, phonenumber , 9157678481}, {country, UK}} from Data Table, which method can be choose? just some tips very be helpful! $\endgroup$
    – lumw
    Dec 1, 2021 at 13:24
  • 1
    $\begingroup$ @Ben, try SequenceCases[data, p : {{userid, Except[1], __}, _} :> Sequence @@ p] or DeleteCases[data, Alternatives @@ SequenceCases[data, p : {{_, 1, __}, _} :> Sequence @@ p]] $\endgroup$
    – kglr
    Dec 1, 2021 at 13:43
  • $\begingroup$ Ace! Thank you so much! $\endgroup$
    – lumw
    Dec 1, 2021 at 13:57
  • 1
    $\begingroup$ Also: Catenate@SequenceCases[data, {{_, 1, __}, _}] $\endgroup$
    – eldo
    Mar 15 at 8:53

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.