Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

I have a list, e.g.:

list = {1, 2, 3, "Element 1", 4, 5, "Element 2", "Something else 1", "etcetera"}

Now, I want all elements starting with "El". Using Position, I could find the position of e.g. "Element 1":

Position[list, "Element 1"]

But, I would like to know the positions of "Element 1" and "Element 2", as both start with "El". So, I would like to have something like

Position[list, "El"_]

I just can't get something like this to work.

Thanks for any help.

share|improve this question
    
You need string patterns and Friends, e.g. StringFreeQ, StringPosition, .. –  Spawn1701D May 10 '13 at 19:03
    
Related: mathematica.stackexchange.com/q/6998/121 –  Mr.Wizard May 11 '13 at 7:58

3 Answers 3

up vote 10 down vote accepted

But I would like to know the positions of "Element 1" and "Element 2"...

You can still use Position[]; things are a little more elaborate, though, due to the strings:

Position[list, s_String /; StringMatchQ[s, "El*"]]
   {{4}, {7}}

Extract[list, %]
   {"Element 1", "Element 2"}
share|improve this answer
    
+1 for reading the question. ;-) –  Mr.Wizard May 11 '13 at 7:57
    
Great! Thanks a lot - that solved it. –  Mockup Dungeon May 11 '13 at 8:02
Select[list, StringMatchQ[ToString@#, "El" ~~ ___] &]

{"Element 1", "Element 2"}

share|improve this answer

A possibility:

Cases[list, x_String /; StringMatchQ[x, "El*"]]
{"Element 1", "Element 2"}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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