【问题标题】:Convert comma-separated string to nested array, RegExp?将逗号分隔的字符串转换为嵌套数组,RegExp?
【发布时间】:2026-01-09 10:40:01
【问题描述】:

得到了这种类型的字符串:

var myString = '23, 13, (#752, #141), $, ASD, (#113, #146)';

我需要将它拆分为一个以逗号作为分隔符的数组,但还要将(..) 转换为一个数组。

这是我想要的结果:[23, 13, ['#752', '#141'], '$', 'ASD', ['#113', '#146']];

我有大量的数据集,因此尽可能快地处理它非常重要。最快的方法是什么?做一些技巧 RegExp 函数还是手动查找索引等?

这是一个 jsbin:https://jsbin.com/cilakewecu/edit?js,console

【问题讨论】:

  • 如果可能,在源头将字符串格式化为真实数组,并使用 JSON.parse 创建数组。
  • 无法修改源代码。

标签: javascript arrays regex


【解决方案1】:

将括号转换为括号,引用字符串,然后使用JSON.parse

JSON.parse('[' + 
  str.
    replace(/\(/g, '[').
    replace(/\)/g, ']').
    replace(/#\d+|\w+/g, function(m) { return isNaN(m) ? '"' + m + '"' : m; })
  + ']')

> [23,13,["#752","#141"],"ASD",["#113","#146"]]

【讨论】:

  • 有趣,但在预期结果中 2313 应该是数字而不是字符串
  • @torazaburo 在我的数据集上尝试过,显然有时 $ 符号出现在我的字符串中。我得到意外的令牌 $。是否有可能以某种方式将其替换为'$'或null?我更新了问题。
  • \w 更改为[\w$]
【解决方案2】:

你可以使用正则表达式

/\(([^()]+)\)|([^,()\s]+)/g

RegEx Explanation:

RegEx 包含两个部分。 首先,捕获括号内的任何内容。 ,捕获简单的值(字符串、数字)

  1. \(([^()]+)\):匹配括号内的任何内容。
    • \(:匹配 ( 字面量。
    • ([^()]+):匹配除() 之外的任何内容一次或多次,并将匹配项添加到第一个捕获的组中。
    • \):匹配 ) 字面量。
  2. |: 正则表达式中的 OR 条件
  3. ([^,()\s]+):匹配除,(逗号)、括号() 之外的任何字符,并空格一次或多次,并将匹配项添加到第二个捕获组中

演示:

var myString = '23, 13, (#752, #141), ASD, (#113, #146)',
    arr = [],
    regex = /\(([^()]+)\)|([^,()\s]+)/g;

// While the string satisfies regex
while(match = regex.exec(myString)) {

    // Check if the match is parenthesised string
    // then
    //     split the string inside those parenthesis by comma and push it in array
    // otherwise
    //     simply add the string in the array
    arr.push(match[1] ? match[1].split(/\s*,\s*/) : match[2]);
}

console.log(arr);
document.body.innerHTML = '<pre>' + JSON.stringify(arr, 0, 4) + '</pre>'; // For demo purpose only

【讨论】:

  • (#752", " #141) 应该是数组
  • @Grundy 之间的正则表达式错误以满足 OP 的 $ 条件,已更新。谢谢!
【解决方案3】:

只需使用split 方法。

var str = '23, 13, (#752, #141), ASD, (#113, #146)',
    newstr = str.replace(/\(/gi,'[').replace(/\)/gi,']'),
    splitstr = newstr.split(',');

【讨论】:

  • 他说由于嵌套数组,在逗号处拆分对他不起作用。