Skip to content

Instantly share code, notes, and snippets.

@constructor-igor
Created April 22, 2015 12:55
Show Gist options
  • Save constructor-igor/5f881c32403e3f313e6f to your computer and use it in GitHub Desktop.
Save constructor-igor/5f881c32403e3f313e6f to your computer and use it in GitHub Desktop.
parsing nested parentheses in python, grab content by level
#http://stackoverflow.com/questions/4284991/parsing-nested-parentheses-in-python-grab-content-by-level
def parenthetic_contents(string):
"""Generate parenthesized contents in string as pairs (level, contents)."""
stack = []
for i, c in enumerate(string):
if c == '(':
stack.append(i)
elif c == ')' and stack:
start = stack.pop()
yield (len(stack), string[start + 1: i])
>>> list(parenthetic_contents('(a(b(c)(d)e)(f)g)'))
[(2, 'c'), (2, 'd'), (1, 'b(c)(d)e'), (1, 'f'), (0, 'a(b(c)(d)e)(f)g')]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment