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

5 Answers 5

6
$\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$
5
$\begingroup$
Cases[{_String?(StringMatchQ["AB*"]), ___}] @ lis
{{"AB", 2, 3}, {"ABC", 8, 9}}
$\endgroup$
3
$\begingroup$

EDIT

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

Select[ListQ@# && StringStartsQ[First@#, "AB"] &][#] &@lis

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


ORIGINAL

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$
1
  • $\begingroup$ Select[ListQ@# && StringStartsQ[First@#, "AB"] &]@lis works, f[#]& @x vs f@x $\endgroup$ May 11, 2023 at 6:28
2
$\begingroup$
list = {1, {"AB", 2, 3}, {"ABC", 8, 9}, {"BC", 7}};

Using SequenceSplit (new in 11.3)

split = SequenceSplit[list, {{x_, __} /; StringTake[x, 2] != "AB"}]

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

Cases[split, {_String, __}, -1]

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

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

Using DeleteCases:

DeleteCases[lis, Except[{str_ /; StringStartsQ[str, "AB"], __} ..]]

(*{{"AB", 2, 3}, {"ABC", 8, 9}}*)
$\endgroup$

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.