[英]Convert comma-separated string to nested array, RegExp?
将括号转换为方括号,引用字符串,然后使用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包含两个部分。 首先 ,捕获括号内的所有内容。 其次 ,捕获简单值(字符串,数字)
\\(([^()]+)\\)
:匹配括号内的任何内容。
\\(
:匹配(
文字 ([^()]+)
:匹配(
和)
以外的任何其他内容一次或多次,并将匹配项添加到第一个捕获的组中。 \\)
:Match )
文字。 |
:RegEx中的OR条件 ([^,()\\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
只需使用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.