8

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.

J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574
Mockup Dungeon
  • 1,854
  • 12
  • 16

5 Answers5

15

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"}
J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574
5
Select[list, StringMatchQ[ToString@#, "El" ~~ ___] &]

{"Element 1", "Element 2"}

Sjoerd C. de Vries
  • 65,815
  • 14
  • 188
  • 323
3

A possibility:

Cases[list, x_String /; StringMatchQ[x, "El*"]]
{"Element 1", "Element 2"}
Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
andre314
  • 18,474
  • 1
  • 36
  • 69
1

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

enter image description here

Some possibilities using StringStartsQ could be:

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

Extract[list, Position[list, _String?(StringStartsQ[#, "El"] &)]]

Cases[list, _String?(StringStartsQ[#, "El"] &)]

Select[list, StringQ] // Select[StringStartsQ["El"]]

Select[list, StringQ[#] && StringStartsQ[#, "El"] &]

SequenceCases[list, {x_String /; StringStartsQ[x, "El"]} :> x]

This being mixed Head list, a pre-selection of String heads is required to silence the warnings and errors.


Result:

{"Element 1", "Element 2"}

Syed
  • 52,495
  • 4
  • 30
  • 85
1

Using DeleteCases and Except:

DeleteCases[list, Except[x_String /; StringStartsQ[x, "El"]]]

({"Element 1", "Element 2"})

E. Chan-López
  • 23,117
  • 3
  • 21
  • 44