8
$\begingroup$

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.

$\endgroup$
15
$\begingroup$

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"}
| improve this answer | |
$\endgroup$
  • $\begingroup$ Great! Thanks a lot - that solved it. $\endgroup$ – Mockup Dungeon May 11 '13 at 8:02
5
$\begingroup$
Select[list, StringMatchQ[ToString@#, "El" ~~ ___] &]

{"Element 1", "Element 2"}

| improve this answer | |
$\endgroup$
3
$\begingroup$

A possibility:

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

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.