简体   繁体   English

使用多个嵌套定界符分割字符串

[英]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. 之后,我将需要再次将其拆分为嵌套括号。

You can split a string using /([\\{\\}])/ regexp and scan the resulting array to extract tokens and depth level. 您可以使用/([\\{\\}])/ regexp分割字符串,然后扫描结果数组以提取标记和深度级别。

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);

use below code 使用以下代码

var a = '{1 (Test)}{2 ({3 (A)}{4 (B)}{5 (C)})}{100 (AAA{101 (X){102 (Y)}{103 (Z)})}';
b = a.replace(/\{/g,'');
c = b.replace(/\}/g,'\n')
console.log(c);

//Results

1 (Test)
2 (3 (A)
4 (B)
5 (C)
100 (AAA101 (X)
102 (Y)
103 (Z))

You can also use the code below to break it into multi-dimensional array; 您还可以使用下面的代码将其分解为多维数组。

 let logic = '(another((checker)check)john)(smith)(jane(does(smith(kline))))'; function getLevel(text) { if (Array.isArray(text)) return text.map(t => getLevel(t)); var d = null, str_split = text.split(/([\\(\\)])/).filter(t => t.trim()), result = [], tr = '', depth = 0, groups = []; if (str_split.length <= 1) return text; for (let i = 0; i < str_split.length; i++) { tr = str_split[i]; //console.log(tr); if (tr === '(') { if (d === null) { if (result.length) groups.push(result.join('')); d = depth; result = []; } depth++; } if (tr === ')') { depth--; } result.push(tr); if (d !== null && d === depth && tr === ')') { let fr = result.join(''); if (fr === text && RegExp('^\\\\(').test(fr) && RegExp('\\\\)$').test(fr)) { let ntext = text.replace(/(^\\(|\\)$)/g, ''); fr = getLevel(ntext); } groups.push(fr); d = null; result = []; } } if (result.length) groups.push(result.join('')); return groups.map(g => getLevel(g)); } let gr = getLevel(logic); console.log(JSON.stringify(gr)); //Expected output: [[["another",[[["checker"],"check"]],"john"]],["smith"],[["jane",[["does",[["smith",["kline"]]]]]]]] 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM