使用多个嵌套分隔符拆分字符串

时间:2014-02-03 09:01:36

标签: javascript regex string split slice

我对此字符串有疑问:

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

我希望使用{分隔第一个分隔符,将}分割为最后一个分隔符,但正如您所见,我有嵌套括号。

如何将此字符串拆分为以下内容:

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

之后,我需要再次为嵌套括号拆分它。

3 个答案:

答案 0 :(得分:1)

您可以使用/([\{\}])/ 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);

答案 1 :(得分:0)

使用下面的代码

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

答案 2 :(得分:0)

您还可以使用下面的代码将其分解为多维数组;

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"]]]]]]]]