Search All of the Math Forum:

Views expressed in these public forums are not endorsed by NCTM or The Math Forum.

Topic: Re: find position in a list made by string by searching incomplete
Replies: 0

 Alexei Boulbitch Posts: 483 Registered: 2/28/08
Re: find position in a list made by string by searching incomplete
Posted: Apr 6, 2013 5:09 AM

I have a list of strings like
list1={{"a", "b something", "a", "a", "b", "c", "b"}
In this list, 'something' is a sting that I will not know in advanced and
there are several spaces between the 'b' and the 'something' in one string.
The number of the spaces is unknown.

I want to find out the position of the this "b something" sting in the
list. So, I did,

Position[list1, "b*"]

and I also tried,
Position[list1,"b"~~___ ]

both of them gave me {} as results.

Also Cases[list1,"b"~~___] or Cases[list1, "b*"] does not work. I can get
the correct position only if I give the exact "b something" as the
searching pattern. What is the easiest way to search with a incomplete
string pattern in this case? Thanks for your help.

Hi,

It will go easily, if you transform the list of strings (or characters) into the list of symbols:

list1 = {"a", "b something", "a", "a", "b", "c", "b"}

{"a", "b something", "a", "a", "b", "c", "b"}

list2 = Map[ToExpression, list1]

{a, b something, a, a, b, c, b}

Now, one can do it by several ways. For instance, this:

Position[list2, (b a_)]

{{2}}

One can use the fact that the special form of "b something" gives it a Head that differs from that of all other terms. Indeed,

{Symbol, Times, Symbol, Symbol, Symbol, Symbol, Symbol}

this item has the head Times, while the others - Symbol. We can, therefore, do the following:

Position[list2, Select[list2, Head[#] == Times &][[1]]]

{{2}}

or otherwise

{{2}}

Have fun, Alexei

Alexei BOULBITCH, Dr., habil.
IEE S.A.
ZAE Weiergewan,
11, rue Edmond Reuter,
L-5326 Contern, LUXEMBOURG

Office phone : +352-2454-2566
Office fax: +352-2454-3566
mobile phone: +49 151 52 40 66 44

e-mail: alexei.boulbitch@iee.lu