Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 378
Raoul Bivolaru Avatar asked Sep 03 '26 05:09

Raoul Bivolaru


1 Answers

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);
like image 119
Yury Tarabanko Avatar answered Sep 05 '26 20:09

Yury Tarabanko