简体   繁体   English

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

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

Got this type of string: 得到了这种类型的字符串:

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

I need to split it to an array with comma as separator but also converts (..) to an array. 我需要将其拆分为一个以逗号作为分隔符的数组,而且还要将(..)转换为数组。

This is the result I want: [23, 13, ['#752', '#141'], '$', 'ASD', ['#113', '#146']]; 这是我想要的结果: [23, 13, ['#752', '#141'], '$', 'ASD', ['#113', '#146']];

I got huge data-sets so its very important to make it as fast as possible. 我有大量的数据集,因此使其尽快变得非常重要。 What's the fastest way? 最快的方法是什么? Do some trick RegExp function or do it manually with finding indexes etc.? 做一些RegExp功能还是通过查找索引等手动完成?

Here's a jsbin: https://jsbin.com/cilakewecu/edit?js,console 这是一个jsbin: https ://jsbin.com/cilakewecu/edit ? js,控制台

Convert the parens to brackets, quote the strings, then use JSON.parse : 将括号转换为方括号,引用字符串,然后使用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"]]

You can use RegEx 您可以使用RegEx

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

RegEx Explanation: RegEx说明:

The RegEx contain two parts. RegEx包含两个部分。 First , to capture anything that is inside the parenthesis. 首先 ,捕获括号内的所有内容。 Second , capture simple values (string, numbers) 其次 ,捕获简单值(字符串,数字)

  1. \\(([^()]+)\\) : Match anything that is inside the parenthesis. \\(([^()]+)\\) :匹配括号内的任何内容。
    • \\( : Match ( literal. \\( :匹配(文字
    • ([^()]+) : Match anything except ( and ) one or more number of times and add the matches in the first captured group. ([^()]+) :匹配()以外的任何其他内容一次或多次,并将匹配项添加到第一个捕获的组中。
    • \\) : Match ) literal. \\) :Match )文字。
  2. | : OR condition in RegEx :RegEx中的OR条件
  3. ([^,()\\s]+) : Match any character except , (comma), parenthesis ( and ) and space one or more number of times and add the match in the second captured group ([^,()\\s]+) :匹配除, (逗号),括号()以外的任何字符,并间隔一或多次,并在第二个捕获组中添加匹配项

RegEx流程图

Demo: 演示:

 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 

Just use the split method. 只需使用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