Python: splitting a complex string including parentheses and |
Question: 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.


Answer: Another suggestion:

    
    
    >>> s = "DATA(VALUE1|VALUE2||VALUE4)"
    >>> import re
    >>> matches = re.findall("[^()]+", s)
    >>> matches
    ['DATA', 'VALUE1|VALUE2||VALUE4']
    >>> result = {matches[0]: matches[1].split("|")}
    >>> result
    {'DATA': ['VALUE1', 'VALUE2', '', 'VALUE4']}
    

