3
$\begingroup$

I have a list:

lis = {1, {"AB", 2, 3}, {"ABC", 8, 9}, {"BC", 7}};

...and I would like to make a new list consisting of all elements of lis that begin with "AB", to make:

res = {{"AB",2,3},{"ABC",8,9}}

This would seem to be a job for SequenceCases, but am not sure how to construct it.

$\endgroup$
4
$\begingroup$

I am sure there are many ways to do this. How about using Cases ?

lis = {1, {"AB", 2, 3}, {"ABC", 8, 9}, {"BC", 7}};
Cases[lis, x_ /; (Head[x] === List && StringStartsQ[First@x, "AB"])]

Mathematica graphics

$\endgroup$
4
$\begingroup$
Cases[{_String?(StringMatchQ["AB*"]), ___}] @ lis
{{"AB", 2, 3}, {"ABC", 8, 9}}
$\endgroup$
1
$\begingroup$

As a test case, I have added an entry at the end:

lis = {1, {"AB", 2, 3}, {"ABC", 8, 9}, {"BC", 7}, {4, "CA"}};

Select lists: (Not necessary but for demo)

f = Cases[#, _List] &

Select lists with first String element (This takes care of the element being a list too)

g = Cases[#, {k_String, x___}] &

First element (which is String) matches a pattern:

h[x_List] := Pick[x, StringMatchQ[First@x, "AB" ~~ ___]]

Execute:

h /@ g @ f@ lis

OR:

Composition[Map[h, #] &, g, f][lis]

OR:

h /@ g @* f @ lis

{{"AB", 2, 3}, {"ABC", 8, 9}}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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