0

I have a string of in Python

str1 = 'abc(1),bcd(xxx),ddd(dfk dsaf)'

How to use re to parse it into an object say 'results' so I can do something like:

for k,v in results:
   print('key = %r, value = %r', (k, v)) 

Thanks.

1
  • 1
    What are you asking? Like... key=abc value=1? Commented Jul 12, 2013 at 1:21

4 Answers 4

2

Something like this, using re.findall:

>>> str1 = 'abc(1),bcd(xxx),ddd(dfk dsaf)'
>>> results = re.findall(r'(\w+)\(([^)]+)\),?',str1)
for k,v in results:
    print('key = %r, value = %r' % (k, v))
...     
key = 'abc', value = '1'
key = 'bcd', value = 'xxx'
key = 'ddd', value = 'dfk dsaf'

Pass it to dict() if you want a dict:

>>> dict(results)
{'bcd': 'xxx', 'abc': '1', 'ddd': 'dfk dsaf'}
Sign up to request clarification or add additional context in comments.

Comments

1

You can also use finditer:

>>> p = re.compile(r'(\w+)\((.*?)\)')
>>> {x.group(1):x.group(2) for x in p.finditer(str1)}
{'bcd': 'xxx', 'abc': '1', 'ddd': 'dfk dsaf'}
>>> 

Comments

0

you could, at a pinch, do it without resorting to regex

 str1 = 'abc(1),bcd(xxx),ddd(dfk dsaf)'
 results = [x.split('(') for x in str1.split(',')]
 results = [(x, y.rstrip(')')) for x, y in results]
 print results
 [('abc', '1'), ('bcd', 'xxx'), ('ddd', 'dfk dsaf')]

Comments

0
str1 = 'abc(1),bcd(xxx),ddd(dfk dsaf)'

import re
d = dict(re.findall('(\w+)\((.*?)\)', str1))
# {'bcd': 'xxx', 'abc': '1', 'ddd': 'dfk dsaf'}

for k,v in d.iteritems():
    # do whatever

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.