Re: find position in a list made by string by searching incomplete
- To: mathgroup at smc.vnet.net
- Subject: [mg130372] Re: find position in a list made by string by searching incomplete
- From: Alexei Boulbitch <Alexei.Boulbitch at iee.lu>
- Date: Sat, 6 Apr 2013 05:09:30 -0400 (EDT)
- Delivered-to: l-mathgroup@mail-archive0.wolfram.com
- Delivered-to: l-mathgroup@wolfram.com
- Delivered-to: mathgroup-newout@smc.vnet.net
- Delivered-to: mathgroup-newsend@smc.vnet.net
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,
Head /@ list2
{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
Position[Head /@ list2, Times]
{{2}}
I guess that one can see also few other ways.
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 at iee.lu