将带有嵌套引号的命令字符串解析为参数和标志



我正试图为Discord bot创建一个命令解析器,以在它收到消息时使用,但我在处理嵌套引号时遇到了问题。我制作了它,这样它就可以解析带有双引号和标志的字符串,但它不处理嵌套引号。

以下是我的要求:

  • 处理双引号
  • 处理嵌套的双引号
  • 句柄标志(可以在!command之后的任何位置(。
    • 没有指定值的标志默认值为true/1

例如,以下字符串:

!command that --can "handle double" quotes "and "nested double" quotes" --as --well=as --flags="with values"

应导致以下参数:commandthathandle doublequotesand "nested double" quotes和以下标志:"can": true"as": true"well": "as""flags": "with values"

以下是我迄今为止所拥有的:

// splits up the string into separate arguments and flags
const parts = content.slice(1).trim().match(/(--w+=)?"[^"]*"|[^ "]+/g)
.map(arg => arg.replace(/^"(.*)"$/, '$1'));
// separates the arguments and flags
const [ 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;
}, [[], {}]);

这当前解析为以下参数:commandthathandle doublequotesand nesteddoublequotes和以下标志:"can": true"as": true"well": "as""flags": "with values"

我修改了第一个RegEx,以允许"位于引用值的中间。以下行:

const parts = content.slice(1).trim().match(/(--w+=)?"[^"]*"|[^ "]+/g)

更改为:

const parts = content.slice(1).trim().match(/(--S+=)?"(\"|[^"])*"|[^ "]+/g)

修改

  • "[^"]*"部分更改为"(\"|[^"])*",以允许"进行验证,从而防止引用的值被前面带有反斜杠的引号终止
  • 我将(--w+=)?中的w更改为S,从而生成(--S+=)?,以允许更多的字母进行验证

最新更新