Skip to content

Instantly share code, notes, and snippets.

@markrwilliams
Created August 4, 2012 07:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markrwilliams/3255410 to your computer and use it in GitHub Desktop.
Save markrwilliams/3255410 to your computer and use it in GitHub Desktop.
IN, OUT = object(), object()
def parse(raw):
state = OUT
parsed = []
count = 0
for c in raw:
if c == '(':
if state is OUT:
cur = []
state = IN
count += 1
continue
elif c == ')' and state is IN:
if count == 1:
parsed.append(''.join(cur))
state = OUT
count -= 1
elif state is IN:
cur.append(c)
return parsed
def test():
cases = ['(a, b, c)(e, f)(g, i, j, k)',
'(a (b) c),(e, f)((g, i), j, k)']
for c in cases:
print parse(c)
test()
# ['a, b, c', 'e, f', 'g, i, j, k']
# ['a b c', 'e, f', 'g, i, j, k']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment