actzlol
actzlol

Reputation: 21

Parsing string using regex python

I want to parse the string into an array using regex in python

Row(Cust ID=1386.0, Last Name=u'Aberdeen', Init=u'F', Street=u'45 Utah Street', City=u'Washington', State=u'DC', Zip=u'20032', Credit=50000.0)

So I would want the an array of data after the equal sign.

What i tried so far

re.findall('\=(.*?)\,', db[0])

Upvotes: 1

Views: 63

Answers (1)

ycx
ycx

Reputation: 3211

Here is a one-liner without using regex version:

origin = '''Row(Cust ID=1386.0, Last Name=u'Aberdeen', Init=u'F', Street=u'45 Utah Street', City=u'Washington', State=u'DC', Zip=u'20032', Credit=50000.0)'''
splitstring = [s.split('=')[1].replace(')','') for s in origin.split(',')]
print (splitstring)
#Output: ['1386.0', "u'Aberdeen'", "u'F'", "u'45 Utah Street'", "u'Washington'", "u'DC'", "u'20032'", '50000.0']

Longer version in case you want to see how the above is formulated:

origin = '''Row(Cust ID=1386.0, Last Name=u'Aberdeen', Init=u'F', Street=u'45 Utah Street', City=u'Washington', State=u'DC', Zip=u'20032', Credit=50000.0)'''
splitbycomma = origin.split(',')
splitbyequal = []
for string in splitbycomma:
    splitbyequal.append(string.split('=')[1].replace(')',''))
print(splitbyequal)
#Output: ['1386.0', "u'Aberdeen'",... '50000.0']

Opted for a non-regex answer because I don't see the need to regex for this. In any case, its easier to do split by comma first and then parse the data via regex if that's your fancy.

Upvotes: 3

Related Questions