Regex to split a line containing commas

How can I break a string with a comma that contains commas in Python? Let say the line:

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

How can I get only four elements after splitting?

+4
source share
2 answers
>>> 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')

In Python3.2 +, you can just use literal_eval(obj).

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

Source: https://habr.com/ru/post/1529378/


All Articles