简体   繁体   中英

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']];

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.?

Here's a jsbin: https://jsbin.com/cilakewecu/edit?js,console

Convert the parens to brackets, quote the strings, then use 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

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

RegEx Explanation:

The RegEx contain two parts. 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.
  2. | : OR condition in RegEx
  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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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