Python: splitting a complex string including parentheses and |

parsing, python, regex, string

Solution

You could do it in one pass with `re.split`:

In [10]: import re

In [11]: line = 'DATA(VALUE1|VALUE2||VALUE4)'

In [12]: re.split(r'[(|)]', line)
Out[12]: ['DATA', 'VALUE1', 'VALUE2', '', 'VALUE4', '']

And extract the data and values like this:

In [13]: parts = re.split(r'[(|)]', line)

In [14]: data = parts[0]

In [15]: values = parts[1:-1]

In [16]: values
Out[16]: ['VALUE1', 'VALUE2', '', 'VALUE4']

Problem

In a test file, I have records in the form ``` DATA(VALUE1|VALUE2||VALUE4) ``` and so on. I'd like to split this string in two passes, the first yielding "DATA", and the second giving me what's inside the parentheses, split at the "|". The second part looks trivial, but so far my attempts at the first were ugly. I'm more inclined towards regex than parsing as lines are quite simple in the end.

Original source