2
$\begingroup$

Consider the following list. I've tried various ways to extract only those pairs in the list where both elements have the string N36. Given the below, the output would be just {N36012,N36321} and {N36040,N36098}. Suggestions are most welcomed!

lst = {{N36061, N35100}, {N36012, N36321}, {N36040, N36098}, {N8100, 
    N36010}}
$\endgroup$

3 Answers 3

4
$\begingroup$
Clear["Global`*"]

lst = {{N36061, N35100}, {N36012, N36321}, {N36040, N36098}, {N8100, N36010}};

Select[lst, 
 And @@ {StringContainsQ[ToString@#[[1]], "N36"], 
    StringContainsQ[ToString@#[[2]], "N36"]} &]

(* {{N36012, N36321}, {N36040, N36098}} *)

Or

Select[lst, AllTrue[#, StringContainsQ[ToString@#, "N36"] &] &]

(* {{N36012, N36321}, {N36040, N36098}} *)
$\endgroup$
1
  • $\begingroup$ Many thanks, Bob ... I wasn't aware of the StringContainsQ ... thank u ...prg $\endgroup$
    – PRG
    Aug 5 at 14:01
3
$\begingroup$

have the string N36.

It you meant starts with "N36" and not has this string anywhere, another option is

lst = {{"N36061", "N35100"}, {"N36012", "N36321"}, {"N36040", "N36098"}, {"N8100", "N36010"}}
pat = "N36" ~~ __;
StringMatchQ[First[#], pat] && StringMatchQ[Last[#], pat] & /@ lst;
Pick[lst, %]

Mathematica graphics

$\endgroup$
1
  • $\begingroup$ Nasser: That is a very nice option too; I was not familiar with your second line of code ... thank u very much! $\endgroup$
    – PRG
    Aug 4 at 17:29
3
$\begingroup$

There is a built in StringStartsQ. You can define a function to determine whether items in a list share a prefix:

PrefixMatch[prefix_String, list_List] := 
  AllTrue[ToString /@ list, StringStartsQ[prefix]]

With that, you can use Select:

Select[lst, PrefixMatch["N36", #] &]
$\endgroup$
1
  • $\begingroup$ PrefixMatch!! very nice ... thank u!! $\endgroup$
    – PRG
    Aug 5 at 14:02

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.