使用正则表达式在 Discord.js 中定义变量?

问题描述

有人建议我在这discord.js 项目中使用正则表达式。它按照键入两个提及的顺序将消息中的两个提及保存到两个变量中。 discord.js 按照实际 ID 的数字顺序读取提及项,而不是实际键入的顺序,因此我们必须改用正则表达式。命令字符串为: f$command @user1 @user2 所以,这是我的代码

else if (command === 'command'){
        const regex = /<@!?(\d+)>/;
        let match = regex.exec(message);
        while (match){
            const User1 = match[1].id;
            const User2 = match[2].id;
        }

这是正确的,我如何使它需要 2 个正则表达式匹配?

解决方法

else if (command === 'command') {
    const regex = /<@!?(\d+)>/;
    let match = regex.exec(message);
    const result = [];
    while (match){
        result.push(match[1]);
        match = regex.exec(message);
    }
    if (result.length !== 2) {
        console.error('not 2 matches');
    }
    const User1 = result[0];
    const User2 = result[1];
}