Perl/PCRE regex, should work in JS too (as long as {} aren't nested):
$_ = 'aaa[bbb,ccc[ddd,{eee:1,mmm:999}],nnn[0,3]]
aaa[bbb,ccc[ddd,{eee:1, mmm:[123,555]}],nnn[0,3]]
aaa[bbb, ccc[ddd, ddd],nnn[0,3]]
aaa[bbb,ddd[0,3]]';
@r = /[^][,{}]+|\{[^}]*}/g;
print join ", ", @r;
Output:
aaa, bbb, ccc, ddd, {eee:1,mmm:999}, nnn, 0, 3,
aaa, bbb, ccc, ddd, {eee:1, mmm:[123,555]}, nnn, 0, 3,
aaa, bbb, ccc, ddd, ddd, nnn, 0, 3,
aaa, bbb, ddd, 0, 3
A rough translation into JavaScript:
var input =
"aaa[bbb,ccc[ddd,{eee:1,mmm:999}],nnn[0,3]]\n" +
"aaa[bbb,ccc[ddd,{eee:1, mmm:[123,555]}],nnn[0,3]]\n" +
"aaa[bbb, ccc[ddd, ddd],nnn[0,3]]\n" +
"aaa[bbb,ddd[0,3]]";
var re = /[^][,{}]+|\{[^}]*}/g;
var result = [];
while (!!(match = re.exec(input)))
{
result.push(match[0]);
}
// Using <<value>> rather than just a comma, for clarity around
// whether and how "{...}" was processed or not.
write("<<" + result.join(">><<") + ">>");
It's not clear what the line breaks in the input or result data in the question are meant to be. In the above, they're line breaks in the input data and then not treated specially in the result. If they need to be treated specially, the OP can edit appropriately. And so this is the result of the above (again, using <<
and >>
as separators rather than ,
for clarity around whether {...}
gets processed):
<<aaa>><<bbb>><<ccc>><<ddd>><<{eee:1,mmm:999}>><<nnn>><<0>><<3>><<
aaa>><<bbb>><<ccc>><<ddd>><<{eee:1, mmm:[123,555]}>><<nnn>><<0>><<3>><<
aaa>><<bbb>><< ccc>><<ddd>><< ddd>><<nnn>><<0>><<3>><<
aaa>><<bbb>><<ddd>><<0>><<3>>