Re: Finding the Position of Elements in a List that Contain a Substring
- To: mathgroup at smc.vnet.net
- Subject: [mg102218] Re: Finding the Position of Elements in a List that Contain a Substring
- From: Bill Rowe <readnews at sbcglobal.net>
- Date: Sat, 1 Aug 2009 04:03:13 -0400 (EDT)
On 7/31/09 at 5:53 AM, gregory.lypny at videotron.ca (Gregory Lypny) wrote: >Suppose I have a list of strings, say, sentences such as >listOfStrings = {"The cat is here.", "It's not here.", "Not in the >catalogue,", "Where is the cat?"} >and a string I want to search for >searchString = "cat" >I can use StringCases to pick off the elements that contain the >search string >StringCases[listOfStrings, __ ~~ searchString ~~ ___] >{{"The cat is here."}, {}, {"Not in the catalogue,"}, {"Where is the >cat?"}} >But what if I just want to know the positions of the elements that >are hits? In this case, it's >{1, 3, 4} One way to do this would be: In[1]:= searchString = "cat"; stringList = {{"The cat is here."}, {}, {"Not in the catalogue,"}, \ {"Where is the cat?"}}; In[3]:= Position[ StringPosition[#, searchString] /. {a_Integer, b_Integer} -> 1 & /@ stringList, {1}][[All, 1]] Out[3]= {1,3,4} The idea here is using StringPosition returns a standard pattern when there is a hit that can be made into any convenient value using pattern matching. Now Position can be use to locate instances of that value returning the desired positions of the hits.