首页 > 解决方案 > 如何使 rex to [ ] 替换或拆分?

问题描述

我将此字符串“root [0] [1] [2]”作为rex。我想要这个字符串数组([root, 0, 1, 2])或字符串(root.0.1.2)。

我试过 make /["["]|["]["]/g. 但是,这个 rex ][ 字符串承认包含 ["]。这个 rex ["["][^"["]* 识别了整个括号。

/["["]|["]["]/g <- 1

或者

/["["][^"["]*/g <- 2

结果2:root[0][1][2][3] => [0],[1],[2],[3]

结果 1:["]["] => 错误

标签: javascriptregex

解决方案


匹配除负字符集[以外的任何内容:]

const str = 'root[0][1][2]';
const matches = str.match(/[^[\]]+/g);
console.log(matches);


推荐阅读