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

Parse command string with nested quotes into arguments and flags

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

这是我的要求:

例如下面的字符串:

!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(/^"(.*)"$/, ''));

// 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(/^"(.*)"$/, '');
    } else {
      parts[1][part.slice(2)] = true;
    }
  } else {
    parts[0].push(part);
  }

  return parts;
}, [[], {}]);

当前解析为以下参数:commandthathandle doublequotesand \nesteddouble\ quotes 和以下标志:"can": true"as": true"well": "as""flags": "with values".

我修改了第一个正则表达式以允许 \" 在引用值的中间。下面一行:

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

...更改为:

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

修改

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