I am trying to get Position work with patterns. I have the following code:

dat = {"star", "u", "g", "r", "i", "z", "star2", "u", "g", "r", "i", 
   "z", "star3", "u", "g", "r", "i", "z", "star4", "u", "g", "r", "i",
    "z", "Astro", "u", "g", "r", "i", "z"};
Position[dat, "star" ~~ _]
Position[dat, RegularExpression["star."]]

Netheir returns anything. What I want is to return position of "star", "star2" etc. How do I properly use patterns with Position?

  • $\begingroup$ @kglr No, this does not return the first one. Also it returns empty fields of dimensions of the original list. I would prefer make it work in the way Position works and also understand why this does not actually work $\endgroup$ – leosenko Jun 13 '16 at 22:01
  • 2
    $\begingroup$ As to the "why?"... Patterns and string patterns are two distinct syntactic forms. Position only supports the former. The reasons for the distinction are discussed in (8945). $\endgroup$ – WReach Jun 14 '16 at 14:20
Position[dat, _String?(StringMatchQ[#, "star" ~~ ___] &)]


Position[dat, _String?(StringMatchQ[#, "star*"] &)]


Position[dat, _?(StringMatchQ[#, "star*"] &), Heads -> False]


Position[StringMatchQ[dat, "star*"], True] (*thanks: @TomD *)

{{1}, {7}, {13}, {19}}


Pick[Range@Length@dat, StringMatchQ[#, "star*"] & /@ dat]

{1, 7, 13, 19}

| improve this answer | |
  • 4
    $\begingroup$ Slight variant: Position[StringMatchQ[#, "star*"], True] &@dat $\endgroup$ – user1066 Jun 13 '16 at 23:51
  • $\begingroup$ @TomD, much nicer, thank you. Updated with that alternative. $\endgroup$ – kglr Jun 13 '16 at 23:56

For large lists, this should be snappy:

Pick[Range@Length@dat, StringTake[dat, UpTo@4], "star"]

and actually, taking advantage of listability,

Pick[Range@Length@dat, StringMatchQ[dat, "star*"]]

is a bit faster it seems...

| improve this answer | |

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.