繁体   English   中英

将逗号分隔的字符串转换为嵌套数组,RegExp?

[英]Convert comma-separated string to nested array, RegExp?

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

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

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

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

我有大量的数据集,因此使其尽快变得非常重要。 最快的方法是什么? 做一些RegExp功能还是通过查找索引等手动完成?

这是一个jsbin: https ://jsbin.com/cilakewecu/edit ? js,控制台

将括号转换为方括号,引用字符串,然后使用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"]]

您可以使用RegEx

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

RegEx说明:

RegEx包含两个部分。 首先 ,捕获括号内的所有内容。 其次 ,捕获简单值(字符串,数字)

  1. \\(([^()]+)\\) :匹配括号内的任何内容。
    • \\( :匹配(文字
    • ([^()]+) :匹配()以外的任何其他内容一次或多次,并将匹配项添加到第一个捕获的组中。
    • \\) :Match )文字。
  2. | :RegEx中的OR条件
  3. ([^,()\\s]+) :匹配除, (逗号),括号()以外的任何字符,并间隔一或多次,并在第二个捕获组中添加匹配项

RegEx流程图

演示:

 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 

只需使用split方法。

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

暂无
暂无

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

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