我正在嘗試為 Discord 機器人創(chuàng)建一個命令解析器,以便在收到消息時使用,但我在處理嵌套引號時遇到問題。我已經(jīng)做到了,它可以解析帶有雙引號和標(biāo)志的字符串,但它不處理嵌套引號。這是我的要求:處理雙引號。處理嵌套雙引號。處理標(biāo)志(可以位于 后的任何位置!command)。沒有指定值的標(biāo)志默認(rèn)值為true/ 1。例如,以下字符串:!command that --can "handle double" quotes "and \"nested double\" quotes" --as --well=as --flags="with values"...應(yīng)該產(chǎn)生以下參數(shù):command、that、handle double、quotes和and "nested double" quotes以下標(biāo)志:"can": true、"as": true、"well": "as"、"flags": "with values"。這是我到目前為止所擁有的:// splits up the string into separate arguments and flagsconst parts = content.slice(1).trim().match(/(--\w+=)?"[^"]*"|[^ "]+/g) .map(arg => arg.replace(/^"(.*)"$/, '$1'));// separates the arguments and flagsconst [ args, flags ] = parts.reduce((parts, part) => { // check if flag or argument if (part.startsWith('--')) { // check if has a specified value or not if (part.includes('=')) { // parses the specified value part = part.split('='); const value = part.slice(1)[0]; parts[1][part[0].slice(2)] = value.replace(/^"(.*)"$/, '$1'); } else { parts[1][part.slice(2)] = true; } } else { parts[0].push(part); } return parts;}, [[], {}]);當(dāng)前解析為以下參數(shù):、command、that、handle double、quotes、and \、nested和以下標(biāo)志:、、、。double\ quotes"can": true"as": true"well": "as""flags": "with values"
將帶有嵌套引號的命令字符串解析為參數(shù)和標(biāo)志
jeck貓
2023-07-29 15:24:05