Skip to content Skip to sidebar Skip to footer

Turn A String With Nested Parenthesis Into A Nested List, Python

There are other questions referring to this on Stack Overflow such as how-to-parse-a-string-and-return-a-nested-array? But they all refer to lists in the format of ((abc)de(fg))).

Solution 1:

Based on this solution by falsetru:

import re

def parse_nested(text, left=r'[(]', right=r'[)]', sep=r','):
    """ Based on https://stackoverflow.com/a/17141899/190597 (falsetru) """
    pat = r'({}|{}|{})'.format(left, right, sep)
    tokens = re.split(pat, text)    
    stack = [[]]
    for x in tokens:
        if not x or re.match(sep, x): continue
        if re.match(left, x):
            stack[-1].append([])
            stack.append(stack[-1][-1])
        elif re.match(right, x):
            stack.pop()
            if not stack:
                raise ValueError('error: opening bracket is missing')
        else:
            stack[-1].append(x)
    if len(stack) > 1:
        print(stack)
        raise ValueError('error: closing bracket is missing')
    return stack.pop()

text = '((wordOneWord2)OtherWord(FinalWord))'
print(parse_nested(text))
# [[['wordOneWord2'], 'OtherWord', ['FinalWord']]]

Post a Comment for "Turn A String With Nested Parenthesis Into A Nested List, Python"