问题
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));
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',]
回答1:
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('", "')}" ]`)
来源:https://stackoverflow.com/questions/62104987/count-content-inside-quotes-as-one-argument