Regular expression for "key = value" pairs

C

Ciccio

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

Mark Wooding

Ciccio said:
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]
 
C

Ciccio

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top