Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Python (http://www.velocityreviews.com/forums/f43-python.html)
-   -   Regular expression for "key = value" pairs (http://www.velocityreviews.com/forums/t740643-regular-expression-for-key-value-pairs.html)

Ciccio 12-22-2010 04:22 PM

Regular expression for "key = value" pairs
 
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')]

Thanks for your help,
francesco.

Mark Wooding 12-22-2010 04:53 PM

Re: Regular expression for "key = value" pairs
 
Ciccio <franapoli@gmail.com> writes:

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

[...]
> In [12]: re.findall(r'(.+)=(.+)', s)
> Out[12]: [('a=b, c', 'd')]


I think there are two logically separate jobs here: firstly, extracting
the comma-separated pairs, and secondly parsing the individual pairs.

If you want the extra problem of dealing with regular expressions, this
seems to be the way to do it.

R_PAIR = re.compile(r'''
^\s*
([^=\s]|[^=\s][^=]*[^=\s])
\s*=\s*
(\S|\S.*\S)
\s*$
''', re.X)

def parse_pair(pair):
m = R_PAIR.match(pair)
if not m:
raise ValueError, 'not a `KEY = VALUE\' pair'
return m.groups([1, 2])

The former is even easier.

R_COMMA = re.compile(r'\s*,\s*')

kvs = [parse_pair(p) for p in R_COMMA.split(string)]

Apply gold-plating to taste.

But actually, it's much easier to avoid messing with regular expressions
at all.

def parse_pair(pair):
eq = pair.index('=')
return pair[:eq].strip(), pair[eq + 1:].strip()

kvs = [parse_pair(p) for p in string.split(',')]

-- [mdw]

Ciccio 12-23-2010 11:07 PM

Re: Regular expression for "key = value" pairs
 
I extracted an isolated problem from a slightly more complex
situation, that's why I'm using REs.
Thank you all for your help, my problem is now solved.


All times are GMT. The time now is 02:14 PM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.