 <p>Here's an ersatz LR lexer/parser (in Python, but porting should be easy). Valid input is assumed.</p> <pre><code>#!/usr/bin/env python3 import re def parse(s): children = {} stack = [] for token in re.findall('[+-]?[0-9]+|.', s): if token == '[': stack.append(n) elif token == ']': del stack[-1] elif token != ',': n = int(token) children[n] = [] if stack: children[stack[-1]].append(n) return children &gt;&gt;&gt; print(parse('2[5],3[6,12[15,16]]')) {16: [], 2: [5], 3: [6, 12], 5: [], 6: [], 12: [15, 16], 15: []} </code></pre>