Fernando Ruscitti
Fernando Ruscitti

Reputation: 37

Python match tuples in string

I have a string with the format:

s = "[(1,2,'foe'), (3,5,'bar'), ...]"

I need to extract each tuple using regular expressions.

I tried stripping '[' and ']' and then apply

re.findall(r'\((\d+),(\d+),(.+)\)', s[1:-1]) 

and other variants but cannot make it work.

Upvotes: 1

Views: 85

Answers (1)

timgeb
timgeb

Reputation: 78690

It looks like you have a list-literal. You don't evaluate those with regex, you throw ast.literal_eval on it and are done.

>>> from ast import literal_eval
>>> literal_eval("[(1,2,'foe'), (3,5,'bar')]")
[(1, 2, 'foe'), (3, 5, 'bar')]

Upvotes: 4

Related Questions