1

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])
5
  • 1
    What have you tried so far? Commented Feb 18, 2019 at 16:20
  • re.findall('\=(.*?)\,', db]) but this doesn't pull the the last one which is credit Commented Feb 18, 2019 at 16:22
  • 1
    Edit your question and put what you've tried there. Not in a comment. Otherwise folks won't see it easily. Your re clearly requires the comma, which the last item doesn't have. What it does have is a ). So try re.findall('\=(.*?)[,)]', db]). Commented Feb 18, 2019 at 16:23
  • oh wow, so when you put [,)], you basically saying the condtion should includes , and ) ? Commented Feb 18, 2019 at 16:27
  • Not exactly. The brackets on [,)] mean , OR ). It's in the regex documentation. Commented Feb 18, 2019 at 16:50

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Updated with a one-liner

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.