MathGroup Archive 2009

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Finding the Position of Elements in a List that

Hi Gregory.

Position[listOfStrings,x_/;StringMatchQ[x, __ ~~ searchString ~~ ___]],

if your list is not too large. If it is, and you want to speed it up, one
solution is to use StringCases (as you did) to produce the list of matches,
and then the <memberPositions> function that I developed in my book:

,see at the bottom of the page - you feed both the original list and the
list of results to it, like this:

StringCases[listOfStrings, __ ~~ searchString ~~ ___]]

I expect this to be fast even for large lists of strings: StringCases is
much faster when used on a whole list of strings rather than used separately
on each string, and my function is also rather fast. I did not benchmark you
problem though, so it is just my guess that this way will be faster than the
first one above.

Hope this helps.


On Fri, Jul 31, 2009 at 1:53 PM, Gregory Lypny
<gregory.lypny at>wrote:

> Hello everyone,
> 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}
> If I use
>        Position[listOfStrings, ___ ~~ theString ~~ ___]
> I get
>        {}
> which is not what I expect.  Also how can I have my searchString
> treated like it is a word so that 3 is not one of the hits?
> Any hints would be much appreciated.
>        Gregory

  • Prev by Date: Re: How to define a list of functions/variables
  • Next by Date: Re: Skellam distribution (solved)
  • Previous by thread: Re: Finding the Position of Elements in a List that
  • Next by thread: Re: Finding the Position of Elements in a List that