1

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.

1
  • N.B: This pattern is not recursive, it's repeating. A recursive one would be like: [(1, [(2, [(3, [...])])])] Commented Nov 22, 2018 at 20:00

1 Answer 1

4

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')]
Sign up to request clarification or add additional context in comments.

1 Comment

thats exactly what I needed!! Thanks very much. Sorry I didn't know about ast module.

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.