将引号中的字符串捕获为单个命令参数 [英] Capture strings in quotes as single command argument

查看:14
本文介绍了将引号中的字符串捕获为单个命令参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个与服务器进行一些交互的 Discord 机器人.

I'm attempting to make a Discord bot that does some interactions with a server.

我已经编写了一些可以工作的代码,但它存在一个大问题.这是我的代码:

I've written some code that sort of works, but there is a big problem with it. Here is my code:

if (command === "file") {

        var accusor = message.author.id;
        var username = args[0];
        var reason = args[1];
        var punishment = args[2];
        var duration = args[3];
        if(!duration) duration = "N/A";
        console.log("Returning last " + amount + " for " + username);
        request.post({url:'http://grumpycrouton.com/kismet/api/post_complaint.php', form: {accusor:accusor,search:username,reason:reason,punishment:punishment,duration:duration}}, function(err,httpResponse,body) { 
            message.reply(body); 
        });
    }

命令是!file {playername} {reason} {punishment} {duration},但问题是,有时一些变量可能有多个单词.例如,{reason} 可能类似于Player had a bad time",但由于参数的拆分方式,我的代码无法正确解析.

The command is !file {playername} {reason} {punishment} {duration}, but the problem is, sometimes a few of the variables may have multiple words. For example, {reason} could be something like "Player had a bad time" but my code is unable to parse this correctly because of the way the arguments are split up.

假设输入了这个命令:

!file GrumpyCrouton "Player had a bad time" Kick "1 Day"但是参数实际上会以不同的方式展开,因为第三个参数中有空格,但正则表达式将所有参数都用空格分割,而不考虑引号.基本上,Discord 会忽略引号并将每个单词用作它自己的参数,从而使 {punishment}{duration} 的参数索引为 6 和 7 而不是 2和 3,因为每个单词都算作参数.

!file GrumpyCrouton "Player had a bad time" Kick "1 Day" But the arguments would actually be spread out differently, because the 3rd argument has spaces in it but the regex splits all of the argument by spaces regardless of quotes. Basically Discord ignores the quotes and uses each word as it's own argument, thus making the {punishment} and {duration} have an argument index that is 6 and 7 instead of 2 and 3, because every word is counted as an argument.

这是我的论点的解读方式:

This is the way my arguments are read:

const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();

我怎样才能使括在引号中的字符串被读取为单个参数而不是多个参数?

How can I make it so strings enclosed in quotes are read as a single argument instead of multiple?

推荐答案

一个简单的正则表达式就可以解决问题 :)

A simple regex will do the trick :)

const input = 'ban user "Look at what you have done!" 7d "This is another string" value';
const regex = new RegExp('"[^"]+"|[\S]+', 'g');
const arguments = [];
input.match(regex).forEach(element => {
    if (!element) return;
    return arguments.push(element.replace(/"/g, ''));
});
console.log(arguments);

/*
 * Use a function with a spreader like:
 * doSomething(...arguments);
 */

这篇关于将引号中的字符串捕获为单个命令参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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