Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

This question already has an answer here:

Sorry for the bad title..Didn't know how to describe this, feel free to change it to be more specific.

I have a list in this form:

list = {"a(0)", "a(1)", "a(2)"}

Now I want the positions of all a* in the list. At first I thought this is easily done with the Position-function, but then I had some difficulties:

Position[list, "a"]

Thought this would work, but somehow I'm missing something. to implement the * to give me all a's regardless of the following characters?

share|improve this question

marked as duplicate by Mr.Wizard Jul 17 '15 at 8:16

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

StringPosition[list, "a"]? – Apple Jul 10 '14 at 11:22
omg..of course! I forgot to transform my list into a string :).. – holistic Jul 10 '14 at 11:30
No need to transform anything. – Kuba Jul 10 '14 at 11:40
up vote 1 down vote accepted

If you really want to use Position :)...

Position[list, s_String?(! StringFreeQ[#, "a"] &)]
{{1}, {2}, {3}}
share|improve this answer
This is nice and I get the correct results. But there is a warning message which I don't understand: StringFreeQ::strse: "String or list of strings expected at position 1 in \!(StringFreeQ[List, \"a\"]). " – holistic Jul 10 '14 at 11:58
Try Position[list, s_String?(! StringFreeQ[#, "a"] &)]. – Kuba Jul 10 '14 at 12:02
works fine now! Can you explain why what the problem was maybe? Want to understand it :) – holistic Jul 10 '14 at 12:04
@holistic Position is scanning everything, Heads too, that's why we had to constrain the pattern. You could also do Position[list, s_?(! StringFreeQ[#, "a"] &), Heads->False] but the method with String is more safe in case of nonstrigs in the list. – Kuba Jul 10 '14 at 12:11
Thank you very much :) – holistic Jul 10 '14 at 12:34
list = {"a(0)", "a(1)", "a(2)"};
StringPosition[list, "a"]

{{{1, 1}}, {{1, 1}}, {{1, 1}}}

share|improve this answer
list = {"a(0)", "a(1)", "a(2)", "b(42)"}

You can get the elements that match like so:

els = Select[list, StringMatchQ[#, "a" ~~ ___] &]

{"a(0)", "a(1)", "a(2)"}

If you want their positions, you can map Position over this list:

Position[list, #] & /@ els

{{{1}}, {{2}}, {{3}}}
share|improve this answer

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