Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 615
Vintage Avatar asked Feb 28 '14 09:02

Vintage


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')

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

like image 87
Ashwini Chaudhary Avatar answered Oct 25 '22 18:10

Ashwini Chaudhary


>>> import re
>>> re.findall(r'\"(.+?)\"', obj)
['alert', 'Sorry, you are not allowed to do that now, try later',
 'success', 'Welcome, user']
like image 1
ndpu Avatar answered Oct 25 '22 19:10

ndpu