Regular expression for "key = value" pairs

André andre.roberge at gmail.com
Wed Dec 22 11:36:27 EST 2010


On Wednesday, December 22, 2010 12:22:22 PM UTC-4, Francesco Napolitano wrote:
> Hi all,
> suppose I have:
> 
> s='a=b, c=d'
> 
> and I want to extract sub-strings a,b,c and d from s (and in general 
> from any longer list of such comma separated pairs).
> Some failed attempts:
> 
> In [12]: re.findall(r'(.+)=(.+)', s)
> Out[12]: [('a=b, c', 'd')]
> 
> In [13]: re.findall(r'(.+?)=(.+)', s)
> Out[13]: [('a', 'b, c=d')]
> 
> In [14]: re.findall(r'(.+)=(.+)*', s)
> Out[14]: [('a=b, c', 'd')]
> 
> In [15]: re.findall(r'(.+)=(.+),', s)
> Out[15]: [('a', 'b')]
> 
> In [16]: re.findall(r'(.+)=(.+),?', s)
> Out[16]: [('a=b, c', 'd')]
> 

How about the following:

>>> s = 'a=b,c=d'
>>> t = []
>>> for u in s.split(','):
...     t.extend(u.split('='))
... 
>>> t
['a', 'b', 'c', 'd']

HTH,

André
> Thanks for your help,
> francesco.




More information about the Python-list mailing list