4 回答

TA貢獻2011條經驗 獲得超2個贊
更新:
因為OP似乎對語言不是很有經驗,所以我選擇提供一個易于閱讀的答案。正確的方法是使用正則表達式捕獲組:https://stackoverflow.com/a/18647776/16805283
這將檢查“message.content”中是否有任何引號,并更改獲取 args 數組的方式。如果未找到引號,它將回退到您自己的代碼以生成 args 數組。請記住,這只有在“message.content”上正好有2個**引號時才有效,因此不應在原因中使用引號
// Fake message object as an example
const message = {
content: '!command "Player name with a lot of spaces" reason1 reason2 reason3'
};
const { content } = message;
let args = [];
if (content.indexOf('"') >= 0) {
// Command
args.push(content.slice(0, content.indexOf(' ')));
// Playername
args.push(content.slice(content.indexOf('"'), content.lastIndexOf('"') + 1));
// Reasons
args.push(content.slice(content.lastIndexOf('"') + 2, content.length));
} else {
args = content.split(' ');
}
// More code using args
如果你想要不帶引號的玩家名稱:
playerName = args[1].replace(/"/g, '');`

TA貢獻1872條經驗 獲得超4個贊
你可以在這里使用正則表達式:
const s = `!command "player one" some reason`;
function getArgsFromMsg1(s) {
const args = []
if ((/^!command/).test(s)) {
args.push(s.match(/"(.*)"/g)[0].replace(/\"/g, ''))
args.push(s.split(`" `).pop())
return args
} else {
return 'not a command'
}
}
// more elegant, but may not work
function getArgsFromMsg2(s) {
const args = []
if ((/^!command/).test(s)) {
args.push(...s.match(/(?<=")(.*)(?=")/g))
args.push(s.split(`" `).pop())
return args
} else {
return 'not a command'
}
}
console.log(getArgsFromMsg1(s));
console.log(getArgsFromMsg2(s));

TA貢獻1772條經驗 獲得超5個贊
我建議你單獨解析命令和它的參數。它將承認編寫更靈活的命令。例如:
var command = msg.content.substring(0, msg.content.indexOf(' '));
var command_args_str = msg.content.substring(msg.content.indexOf(' ') + 1);
switch(command) {
case '!command':
var player = command_args_str.substring(0, command_args_str.lastIndexOf(' '));
var reason = command_args_str.substring(command_args_str.lastIndexOf(' ') + 1);
break;
}

TA貢獻1833條經驗 獲得超4個贊
這是可能的,但對于機器人的用戶來說,只使用不同的字符來拆分兩個參數可能不那么復雜。
例如 如果您知道(或 ,等)不是有效用戶名的一部分。!command player one, reasons,|=>
如果您只支持用戶名部分的引號,則更容易:
const command = `!command`;
const msg1 = {content: `${command} "player one" reasons ggg`};
const msg2 = {content: `${command} player reasons asdf asdf`};
function parse({content}) {
if (!content.startsWith(command)) {
return; // Something else
}
content = content.replace(command, '').trim();
const quotedStuff = content.match(/"(.*?)"/);
if (quotedStuff) {
return {player: quotedStuff[1], reason: content.split(`"`).reverse()[0].trim()};
} else {
const parts = content.split(' ');
return {player: parts[0], reason: parts.slice(1).join(' ')};
}
console.log(args);
}
[msg1, msg2].forEach(m => console.log(parse(m)));
添加回答
舉報