簡體   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