javascriptregexstringsplitslice

Split string using multiple nested delimiters


I have a problem with this string:

{1 (Test)}{2 ({3 (A)}{4 (B)}{5 (C)})}{100 (AAA{101 (X){102 (Y)}{103 (Z)})}

I want to split it using { for the first delimiter and } for the last delimiter, but as you can see I have nested brackets.

How can I split this string to have something like this:

1 (Test)
2 ({3 (A)}{4 (B)}{5 (C)})
100 (AAA{101 (X){102 (Y)}{103 (Z)})

And after that I will need to split it again for the nested brackets.


Solution

  • You can split a string using /([\{\}])/ regexp and scan the resulting array to extract tokens and depth level.

    var string = "{1 (Test)}{2 ({3 (A)}{4 (B)}{5 (C)})}{100 (AAA{101 (X){102 (Y)}{103 (Z)})}";
    var tokens = string.split(/([\{\}])/),
      result = [],
      depth = 0;
    
    tokens.forEach(function scan(token) {
      if (!token) return;
      if (token === "{") {
        depth++;
        return;
      }
      if (token === "}") {
        depth--;
        return;
      }
      result.push({
        depth: depth,
        token: token
      });
    
    });
    console.dir(result);