Parsing parameters with quotes

Sean Ross sross at connectmail.carleton.ca
Thu Mar 13 21:53:26 EST 2003


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.

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
>
>






More information about the Python-list mailing list