ha22109
ha22109

Reputation: 8336

parsing in python

I have following string

adId:4028cb901dd9720a011e1160afbc01a3;siteId:8a8ee4f720e6beb70120e6d8e08b0002;userId:5082a05c-015e-4266-9874-5dc6262da3e0

I need only the value of adId,siteId and userId. means

4028cb901dd9720a011e1160afbc01a3

8a8ee4f720e6beb70120e6d8e08b0002

5082a05c-015e-4266-9874-5dc6262da3e0

all the 3 in different variable or in a array so that i can use all three

Upvotes: 3

Views: 1167

Answers (4)

Andre Miller
Andre Miller

Reputation: 15533

You could do something like this:

input='adId:4028cb901dd9720a011e1160afbc01a3;siteId:8a8ee4f720e6beb70120e6d8e08b0002;userId:5082a05c-015e-4266-9874-5dc6262da3e0'

result={}
for pair in input.split(';'):
    (key,value) = pair.split(':')
    result[key] = value

print result['adId']
print result['siteId']
print result['userId']

Upvotes: 1

Aiden Bell
Aiden Bell

Reputation: 28384

matches = re.findall("([a-z0-9A-Z_]+):([a-zA-Z0-9\-]+);", buf)

for m in matches:
    #m[1] is adid and things
    #m[2] is the long string.

You can also limit the lengths using {32} like

([a-zA-Z0-9]+){32};

Regular expressions allow you to validate the string and split it into component parts.

Upvotes: 1

helloandre
helloandre

Reputation: 10721

There is an awesome method called split() for python that will work nicely for you. I would suggest using it twice, once for ';' then again for each one of those using ':'.

Upvotes: 0

Ants Aasma
Ants Aasma

Reputation: 54925

You can split them to a dictionary if you don't need any fancy parsing:

In [2]: dict(kvpair.split(':') for kvpair in s.split(';'))
Out[2]:
{'adId': '4028cb901dd9720a011e1160afbc01a3',
 'siteId': '8a8ee4f720e6beb70120e6d8e08b0002',
 'userId': '5082a05c-015e-4266-9874-5dc6262da3e0'}

Upvotes: 18

Related Questions