将引号内的内容作为一个参数计算 [英] Count content inside quotes as one argument

查看:62
本文介绍了将引号内的内容作为一个参数计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用node.js的discord.js模块制作一个discord机器人,我有一个基本的参数检测系统,该系统使用空格作为分隔符并将不同的参数放入数组中,这是代码的重要部分.(我正在使用 module.exports 使用单独的命令模块).

I'm making a discord bot with node.js's discord.js module, I have a basic arguments detection system that uses the whitespace as the separator and puts the different arguments in an array, here's the important part of my code. (I'm using separate command modules using module.exports).

const args = message.content.slice(prefix.length).split(/ +/);
const commandName = args.shift().toLowerCase();
const command = client.commands.get(commandName) || client.commands.find(cmd => cmd.alias && cmd.alias.includes(commandName));

例如,当有人写!give foo 50 bar 时.args数组是 ['foo','50','bar']
我希望 args 不要在命令中分割命令的引号部分,这意味着如果有人写!give"foo1 bar1" 50"foo2 bar2" .我希望 args 返回这样的数组,例如 ['foo1 bar1','50','foo2 bar2'] 而不是 ['foo1','bar1','50','foo2','bar1',]

So for example when someone writes !give foo 50 bar. the args array is ['foo','50','bar']
I want the args to not divide quoted parts of the command in the command, meaning if somenoe writes !give "foo1 bar1" 50 "foo2 bar2". I want the args to return an array like this ['foo1 bar1', '50','foo2 bar2'] instead of ['foo1','bar1','50','foo2','bar1',]

推荐答案

这可能不是最有效的方法,但我认为这是可以理解的:我们可以扫描每个字符并跟踪我们是否在里面或在两个引号之外,如果是这样,我们将忽略空格.

This may not be the most efficient way to do it, but I think it's comprehensible: we can scan every character and we keep track of whether we're inside or outside a couple of quotes and, if so, we ignore the spaces.

function parseQuotes(str = '') {
  let current = '',
    arr = [],
    inQuotes = false
    
  for (let char of str.trim()) {
    if (char == '"') {
      // Switch the value of inQuotes
      inQuotes = !inQuotes
    } else if (char == ' ' && !inQuotes) {
      // If there's a space and where're not between quotes, push a new word
      arr.push(current)
      current = ''
    } else {
      // Add the character to the current word
      current += char
    }
  }
      
  // Push the last word
  arr.push(current)
    
  return arr
}

// EXAMPLES
// Run the snippet to see the results in the console

// !give "foo1 bar1" 50 "foo2 bar2"
let args1 = parseQuotes('!give "foo1 bar1" 50 "foo2 bar2"')
console.log(`Test 1: !give "foo1 bar1" 50 "foo2 bar2"\n-> [ "${args1.join('", "')}" ]`)

// !cmd foo bar baz
let args2 = parseQuotes('!cmd foo bar baz')
console.log(`Test 2: !cmd foo bar baz\n-> [ "${args2.join('", "')}" ]`)

// !cmd foo1 weir"d quot"es "not closed
let args3 = parseQuotes('!cmd foo1 weir"d quot"es "not closed')
console.log(`Test 3: !cmd foo1 weir"d quot"es "not closed\n-> [ "${args3.join('", "')}" ]`)

这篇关于将引号内的内容作为一个参数计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆