[英]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.