Parsing parameters with quotes
Bengt Richter
bokr at oz.net
Sat Mar 15 17:09:38 EST 2003
On Thu, 13 Mar 2003 21:53:26 -0500, "Sean Ross" <sross at connectmail.carleton.ca> wrote:
>Hi.
>
>This is close to doing what you want:
>
>>>> import re
>>>> p = re.compile(r'".*?"|\S+')
>>>> s = 'foo "this is one" and this not'
>>>> p.findall(s)
>['foo', '"this is one"', 'and', 'this', 'not']
>
>Unfortunately, "this is one" still has quotes. so you can do
>
>>>> seq = p.findall(s)
>>>> q = re.compile(r'"')
>>>> seq = [q.sub('', word) for word in seq]
>>>> seq
>['foo', 'this is one', 'and, 'this', 'not']
>
>or you can mess around with some other regular expressions.
>
plus a listcomp, e.g. [1] below (to avoid further compounding the top posting)
>hope this helps
>Sean
>
>
>
>"Giovanni Bajo" <noway at sorry.com> wrote in message
>news:Ywaca.11032$Lr4.323544 at twister2.libero.it...
>> Hello,
>>
>> My input is:
>>
>> 'foo "this is one" and this not':
>>
>> and I want to output:
>>
>> ["foo", "this is one", "and", "this", "not"]
>>
>> Basically, a string.split() but must take into account quotes used to
>group
>> as a single word (no escaping is supported within quotes). Now, is there
>> already something in the python library to do this? My code is a bit
>longer
>> than I would have expected:
>>
>> def SplitParms(s):
>> s = s.split('"')
>>
>> L = []
>> for i,t in zip(range(0,len(s)), s):
>> if t:
>> if i%2 == 1:
>> L.append(t.strip())
>> else:
>> L.extend(t.split())
>>
>> return L
>>
>> Is there any faster way? getopt() does not seem to do this (it's done
>> beforehand by whoever fills sys.argv[])
>>
>> Thanks.
>>
>> Giovanni Bajo
>>
>>
[1]
>>> s = 'foo "this is one" and this not'
>>> p = re.compile(r'"(.*?)"|(\S+)')
>>> [g1 or g2 for g1,g2 in p.findall(s)]
['foo', 'this is one', 'and', 'this', 'not']
Regards,
Bengt Richter
More information about the Python-list
mailing list