My vote is also for XML or JSON or another format if you have the ability to control the format. But lacking that, here's a Python implementation of the parser because I was bored.
class ExprParser(object):
current = []
list_stack = []
def __init__(self):
pass
def parse(self,input):
for atom in [s.strip() for s in input.split(',')]:
self.parse_atom(atom)
return self.current
def do_pushes(self,atom):
""" Strip off the '[' and push new lists """
i = 0
while i < len(atom) and atom[i] == '[':
self.push()
i += 1
return atom[i:]
def do_pops(self,atom):
""" Pop the lists """
i = 0
while i < len(atom) and atom[i] == ']':
self.pop()
i += 1
def parse_atom(self,atom):
push_start = atom.find('[')
rest = self.do_pushes(atom[push_start:]) if push_start >= 0 else atom
pop_start = rest.find(']')
val = rest[:pop_start] if pop_start >= 0 else rest
self.add(val)
if pop_start >= 0:
self.do_pops(rest[pop_start:])
def push(self):
self.current = []
self.list_stack.append(self.current)
def pop(self):
done = self.list_stack.pop()
self.current = self.list_stack[-1] if self.list_stack else done
if self.current is not done:
self.add(done)
def add(self,val):
self.current.append(val)
Use like:
parser = ExprParser()
parser.parse('[One, Two[A, B[i, ii, iii, iv], C], Three]')
No error handling though for malformed input.