1

I have a string such as: (1,2,3,'4.1),(4.2)',5,6,7),(8,9,10). The output I need to obtain is the list: [ ((1,2,3,'4.1),(4.2)',5,6,7), (8,9,10) ] I believe I need a regex in order to perform this task. How can I do so?

Thank you.

  • Yes, Regex can help you doing that. Does the pattern you mentioned (`(1,2,3,'4.1),(4.2)',5,6,7),(8,9,10)`) can change (numbers, structure, etc.)? – PhilDulac Jun 03 '16 at 17:29
  • Yes, it can change. In reality it is a long string. I need to parse out each of the strings inside the outermost parentheses. – Devin Roberts Jun 03 '16 at 17:37
  • 1
    @PhilDulac Actually, (arbitrarily deeply) nested parenthetical expressions are a canonical context-free example that regular expressions cannot capture: http://stackoverflow.com/questions/133601/can-regular-expressions-be-used-to-match-nested-patterns – user2390182 Jun 03 '16 at 17:56

1 Answers1

2

You might be able to evaluate the string directly (after putting it in a list).

from ast import literal_eval

string = "(1,2,3,'4.1),(4.2)',5,6,7),(8,9,10)"

literal_eval('[{}]'.format(string))
# [(1, 2, 3, '4.1),(4.2)', 5, 6, 7), (8, 9, 10)]
Jared Goguen
  • 8,772
  • 2
  • 18
  • 36