Vintage
Vintage

Reputation: 238

Regex for splitting a string which contains commas?

How could I split a string by comma which contains commas itself in Python? Let's say the string is:

object = """{"alert", "Sorry, you are not allowed to do that now, try later", "success", "Welcome, user"}"""

How do I make sure I only get four elements after splitting?

Upvotes: 5

Views: 400

Answers (2)

ndpu
ndpu

Reputation: 22571

>>> import re
>>> re.findall(r'\"(.+?)\"', obj)
['alert', 'Sorry, you are not allowed to do that now, try later',
 'success', 'Welcome, user']

Upvotes: 1

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251146

>>> from ast import literal_eval
>>> obj = '{"alert", "Sorry, you are not allowed to do that now, try later", "success", "Welcome, user"}'
>>> literal_eval(obj[1:-1])
('alert', 'Sorry, you are not allowed to do that now, try later', 'success', 'Welcome, user')

On Python3.2+ you can simply use literal_eval(obj).

Upvotes: 5

Related Questions