如果没有涉及到嵌套的话,用正则就行,如果涉及到多层嵌套就比较麻烦了,内部括号里的逗号和普通的逗号不太好区分,比如[A, [B, C]]内部以逗号分隔会分成'A'、'[B'、'C]'。感觉得写个简单的解析器,规则很容易总结:S -> [I, ...]I -> s | Sclass StrArrParser { constructor(str) { this.str = str; this.result= [] this.index = 0; this.parse() } parse() { if(!this.str[this.index]) return; this.index = this.getNonBlankIndex(); if(this.index<0) { throw new Error('格式错误') } if(this.str[this.index] === '[') { this.parseArr() } else { this.parseStr() } } getResult() { return this.result[0]||[]; } getNextIndex(rule) { const checkRule = typeof rule === 'string' ? (s) => s === rule : (s) => rule.test(s) let index = this.index while(this.str[index]) { if(checkRule(this.str[index])) return index index++ } return -1 } getNonBlankIndex() { return this.getNextIndex(/\S/) } getArrStrContent() { if(this.str[this.index] !== '[') { throw new Error('判断错误') } const stack = ['['] let index = this.index + 1 while(this.str[index] && stack.length) { if(this.str[index] === '[') { stack.push('[') } if(this.str[index] === ']') { stack.pop() } index++ } if(stack.length) throw new Error('格式错误') return { str: this.str.substring(this.index+1, index), end: index - 1 } } parseArr() { const {str, end} = this.getArrStrContent(); const parser = new StrArrParser(str); this.result.push(parser.result) this.index = end + 1; this.parse() } parseStr() { const start = this.index; const end = this.getNextIndex(/,|\]/) const rst = this.str.substring(start, end).trim(); rst && this.result.push(rst); this.index = end + 1 this.parse() } }
如果没有涉及到嵌套的话,用正则就行,如果涉及到多层嵌套就比较麻烦了,内部括号里的逗号和普通的逗号不太好区分,比如
[A, [B, C]]
内部以逗号分隔会分成'A'、'[B'、'C]'
。感觉得写个简单的解析器,规则很容易总结:S -> [I, ...]
I -> s | S